【发布时间】:2020-07-11 19:51:21
【问题描述】:
我的项目中有两个主要架构,存储和用户。
-
MongoDB Compass中显示的用户集合如下:
_id : ObjectId("**5e830006c4cec2586875124b**") hearts : Array storeID : Array email : "test@test.com" name : "My name is Test" photo : "fa75fa97-c5d8-4e63-a9ee-38441774a26e.jpeg" slugAuthor : "my-name-is-test" description : "My description is Test" hash : "b841b82dcffdd0d517b5010d9ff2047ab447751a4e6dd573f9d55af..." salt : "2bb0f785b134af11d7ca08d4086801fd880626498fbcf106c0df9a66" __v : 0 -
MongoDB Compass中显示的Store集合如下:
_id : ObjectId("5e830050c4cec2586875124c") tags : Array name : "My activity is Test" description : "My description us Test" participants : 1 duree : 1 date : 2220-02-22T21:02:00.000+00:00 author : ObjectId("**5e830006c4cec2586875124b**") created : 2020-03-31T08:33:20.234+00:00 slug : "my-activity-is-test" __v : 0
我需要什么:
当我显示用户信息时,我还想搜索他创建的每个商店。
如您所见,User id 在 Store 集合中找到 (author: ObjectId).
当我点击路线http://..../store/my-name-is-test/5e830006c4cec2586875124b 时,我需要显示这些信息(用户 + 属于用户的商店列表)。在我的路线中,我需要将“slugAuthor”和“作者:ObjectId”显示为 slug。 (这已经被管理了)。
我已经尝试过的(使用 .populate()):
在我的商店架构中:
author: {
type: mongoose.Schema.ObjectId,
ref: 'User',
}
在我的用户架构中:
listStores: [{
type: mongoose.Schema.ObjectId,
ref: 'Store'}],
在我的控制器中:
exports.myProfil = async (req, res) => {
const user = await User.findOne({slugAuthor: req.params.slugAuthor}).populate('listStores')
res.render('my-profil', {user});
};
它让我可以访问以下数据:
{
"hearts": [],
"listStores": [],
"_id": "5e830006c4cec2586875124b",
"email": "test@test.com",
"name": "My name is Test",
"photo": "fa75fa97-c5d8-4e63-a9ee-38441774a26e.jpeg",
"slugAuthor": "my-name-is-test",
"description": "My description is Test",
"__v": 0
}
如您所见,“listStores”数组是空的,但我需要用该用户创建的每个商店来填充它。
请您在这里帮助我,
非常感谢
【问题讨论】:
-
在指南针中,您的用户只有
storeID,而不是listStores字段。 -
您是否明确地
$push将商店 id 放入创建它的用户的listStore数组中?如果你是,那么这个填充应该可以工作。如果您只是将创建者保存在商店中,那么您可能希望listStore作为 virtual -
@CuongLeNgoc 谢谢,但这不是问题。只是拼写错误。 @als:不,我没有用过
$push,只是救了作者。我尝试过虚拟,但它似乎不起作用。也许我做错了:userSchema.virtual('listStoresAuthor', { ref : 'Store', localField: '_id', foreignField: 'author._id', });
标签: node.js mongodb mongoose aggregation populate