我在一个文件"test.js“中有下面的代码,在其中我试图填充story.fans[0].stories[0],但是它不起作用。其余代码运行良好,但当它试图填充扇子对象故事时,它似乎不起作用。猫鼬可以插2级子对象吗?
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://localhost:27017/testMongoose');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Story.
findOne({ title: 'Casino Royale' }).populate('fans').
exec(function (err, story) {
if (err) return handleError(err);
console.log('the story is',story.title);
console.log('The fans[0] is %s', story.fans[0].name);
story.fans[0].populate('stories');
console.log('the story written by fan is',story.fans[0].stories[0].title);
//option2
story.fans[0].populate('stories').exec(function(err,fan){
console.log('the story written by fan is',fan.stories[0].title);
});
});
}以下是错误消息:

-这是我的故事集
/* 1 */
{
"_id" : ObjectId("61cfd221256ef6d903523700"),
"author" : ObjectId("61cfd221256ef6d9035236fe"),
"title" : "Casino Royale",
"fans" : [
ObjectId("61cfee8b5059fb3fe37b3c5f")
],
"__v" : 1
}
/* 2 */
{
"_id" : ObjectId("61d09887abeb41f82a7e1678"),
"author" : ObjectId("61cfee8b5059fb3fe37b3c5f"),
"title" : "Story 001",
"fans" : [],
"__v" : 0
}这是我的人民收藏
/* 1 */
{
"_id" : ObjectId("61cfd221256ef6d9035236fe"),
"name" : "Ian Fleming",
"age" : 50,
"stories" : [],
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("61cfee8b5059fb3fe37b3c5f"),
"name" : "Fan 001",
"age" : 38,
"stories" : [
ObjectId("61d09fbfbd8f3fa20beaa616")
],
"__v" : 14
}发布于 2022-01-01 20:40:52
考虑到您提供的数据,第二层中没有任何要填充的内容,因为Fan 001中引用的id与任何故事都不匹配。
Fans stories:
61d09fbfbd8f3fa20beaa616
==> is not found in
Available stories:
61d09887abeb41f82a7e1678
61cfd221256ef6d903523700但是,如果您修改了引用,那么您想要使用的就是deep Population
基本上,您在刚填充的对象中填充了一个字段。
然后您的代码如下所示:
Story.findOne({ title: 'Casino Royale' })
.populate({ path: 'fans', model: 'Person', populate: { path: 'stories', model: 'Story' } }).
exec(function(err, story) {
if (err) return handleError(err);
console.log(story)
console.log('the story is', story.title);
console.log('The fans[0] is %s', story.fans[0].name);
console.log('the story written by fan is', story.fans[0].stories[0].title);
});我重新构建了这个示例,但是修正了引用,输出现在看起来是预期的:

https://stackoverflow.com/questions/70551153
复制相似问题