目前我有3种模式:
UserFavorite (应该使用此架构存储用户确定的收藏夹)
var UserFavoriteSchema = new Schema({
_id: {
type: Schema.ObjectId,
auto: true
},
favoriteId: {
type: Schema.ObjectId,
required: true
},
userId: {
type: Schema.ObjectId,
required: true
}
});
module.exports = mongoose.model('UserFavorite', UserFavoriteSchema);
收藏夹(此架构包含系统中可用的收藏夹)
var FavoriteSchema = new Schema({
_id: {
type: Schema.ObjectId,
auto: true
},
storeId: {
type: String,
auto: true
},
name: {
type: String,
required: true
},
...
});
module.exports = mongoose.model('Favorite', FavoriteSchema);
用户架构
var UserSchema = new Schema({
_id: {
type: Schema.ObjectId,
auto: true
},
name: {
type: String,
required: true
},
password: {
type: String,
required: true
},
...
});
module.exports = mongoose.model('User', UserSchema);
每次用户收藏一个项目(来自收藏夹)时,我都会将ID存储在UserFavorite中。
我的问题: 我正在尝试从给定的用户检索所有喜欢的数据(UserFavorite上显示的来自“收藏夹”的所有信息)。
这是我的代码:
UserFavorite.aggregate([
{
$match: {
"userId": mongoose.Types.ObjectId(userId)
}
},
{
$lookup: {
"from": "favorites",
"localField": "favoriteId",
"foreignField": "_id",
"as": "favorites"
}
}
]).exec(function (err, data) {
if(err){
//ERROR
}else{
//Everything's okay
}
});
我的预期结果:
我希望收藏夹数组中包含每个用户收藏夹。 (来自Lookup的“ as”),如下所示:
[
{
"userId": "5bc74f4ac42a2719b8827404",
"favorites": [
{
"_id": "5bc7d92f4235972ea805664e",
"thumbnail": "string",
"storeId": "string",
"name": "string",
},
{
"_id": "5bc7d9414235972ea805664f",
"thumbnail": "no_image",
"storeId": "1234",
"name": "Fulério Store",
}
]
},
]
但是我得到的是:
[
{
"userId": "5bc74f4ac42a2719b8827404",
"favoriteId": "5bc7d92f4235972ea805664e",
"favorites": [
{
"_id": "5bc7d92f4235972ea805664e",
"thumbnail": "string",
"storeId": "string",
"name": "string",
"__v": 0
}
]
},
{
"userId": "5bc74f4ac42a2719b8827404",
"favoriteId": "5bc7d9414235972ea805664f",
"favorites": [
{
"_id": "5bc7d9414235972ea805664f",
"thumbnail": "no_image",
"storeId": "1234",
"name": "Fulério Store",
"__v": 0
}
]
}
]
它将带来“ UserFavorite”的每个收藏夹的信息,而不是将来自给定用户的所有收藏夹放入数组中。
我如何使它工作?
提前谢谢!
答案 0 :(得分:0)
您需要使用$ group运算符,您现在所拥有的类似于
尝试将其添加为聚合的最后阶段
{
$group: {
_id: "$userId",
favoriteArray: {$addToSet: "$favorites"}
}
}
$ group阶段将根据userId将它们全部汇总