Javascript 猫鼬复合种群
我确实找到了一个按id发布的帖子,并进行了控制台日志输出,结果是:Javascript 猫鼬复合种群,javascript,mongoose,Javascript,Mongoose,我确实找到了一个按id发布的帖子,并进行了控制台日志输出,结果是: { comments: [ 5c263bf01b764a11c479f69c, 5c263c41133ace1655edee76 ], _id: 5c263bc61b764a11c479f69b, title: 'good laptop', category: 'Laptop', brand: 'dell', Condition: 'Good Condition', image: 'https://avi
{ comments: [ 5c263bf01b764a11c479f69c, 5c263c41133ace1655edee76 ],
_id: 5c263bc61b764a11c479f69b,
title: 'good laptop',
category: 'Laptop',
brand: 'dell',
Condition: 'Good Condition',
image: 'https://avisassets.abgemea.com/.imaging/flexibleIntroLarge/dms/DMS/local/ZA/fleet/fleet-page/luxury-cars-feature.jpg',
price: 2000,
priceState: 'Negociable',
city: 'Algiers',
phone: '71717171555',
email: 'test@test.com',
description: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
date: '28/11/2018',
userId: 5c25344c321f0d5a777ace00,
__v: 2 }
我确实读过mongoose文档中关于
填充
,但是我没有弄清楚如何填充用户ID
,如何填充注释
,以及注释下嵌套的用户ID假设用户ID
是帖子
模式中的一个字段,您可以这样做:
Posts.findOne({ id: 'your-post-id' })
.populate('userId')
.populate({ path: 'comments',
populate: { path: 'userId',
model:'User' }
})
.exec(callback);
您的架构应与此类似:
var postsSchema = new Schema({
comments: { type: [Schema.ObjectId], ref: 'Comment' },
userId: { type: Schema.ObjectId, ref: 'User' },
...
});
var commentsSchema = new Schema({
userId: { type: Schema.ObjectId, ref: 'User' },
...
});
很高兴我能帮忙:)