【发布时间】:2020-10-25 03:51:08
【问题描述】:
我目前正在使用 mongoose 进行一个项目,但我遇到了 mongoose populate() 方法的问题。
问题是我无法在数组中的对象内填充对象。
// * I simplified the code below.
// Profile Document
Profile = model('Profile', new Schema({
_user: {
type: Schema.Types.ObjectId,
ref: 'User',
},
posts: [
{
type: Schema.Types.ObjectId,
ref: 'Post',
// Post = {
// _id: Number,
// _poster: {
// type: Schema.Types.ObjectId,
// ref: 'User',
// }
// };
},
],
}));
// app.js
const profile = await Profile.findOne({ _user: userId })
.populate('_user') // it works
.populate('posts') // it works too
.populate('posts._poster'); // it doesn't work
有没有办法在数组中填充嵌套对象?
如果你能回答我的问题,那就太好了。提前谢谢你。
我尝试正确访问符号以填充 *_poster*,但是它仍然无法正常工作。代码如下。
const profile = await Profile.findOne({ _user: userId })
.populate('_user')
.populate('posts');
await profile.toObject();
profile.posts.forEach((post) => {
profile.populate('posts.post._poster');
})
【问题讨论】:
-
您的
_poster在您的数据结构中被注释掉了。此外,如果posts是一个数组,我没有看到您指定索引来访问数组的元素。为什么点符号在这种情况下会起作用? -
我注释掉只是为了澄清模型内部,很抱歉让您感到困惑。在获取对象 JavaScript 对象后,我尝试访问该符号,但是,它不能用作 JavaScript 对象并且无法填充。
标签: node.js mongoose mongoose-populate