I am currently using an aggregate lookup method from mongoose and it works:
const data = await this.messageModel.aggregate([ { $match: { channel_id: channel_id }, }, { $limit: limit ? limit : 1000, }, ]).lookup({ from: 'users', localField: 'author', foreignField: 'id', as: 'author', pipeline: [ { $project: { _id: 0, password: 0, email: 0, __v: 0 } } ], });
The data returns an array of object like this
{ "_id": "622861fe264eaed05a32bb2d", "channel_id": "5850473746686541647", "author": [ { "username": "UnusualAbsurd", "status": "Working...", "createdAt": "2022-03-08T14:02:53.728Z", "id": "1" } ], "id": "5850638795510120271", "createdAt": "2022-03-09T08:14:54.228Z", "attachments": [], "content": "zazaza", "__v": 0 }
Now the problem is, the author object that I used the lookup()
method on returns as an array. How do I make it not return as an array?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use $unwind after lookup like this:
{$unwind: '$author'}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0