[英]Mongoose Node Js Join two collections
I am new to MEAN Stack and I am developing application using Node Js. 我是MEAN Stack的新手,正在使用Node Js开发应用程序。
I have two collections say, 我有两个收藏说
var personSchema = Schema({ _id: Number, name: String, age: Number, stories: { type: Array, ref: 'Story' } }); var storySchema = Schema({ _creator: { type: Number }, story_id: String, fans: [{ type: Number }] }); var Story = mongoose.model('Story', storySchema); var Person = mongoose.model('Person', personSchema);
In Person
schema, the stories
is a list of story_id
which is an array of values. 在“ Person
模式中, stories
是story_id
的列表,该列表是一个值数组。 I need to list out all the persons data with their stories details also. 我还需要列出所有人员数据以及他们的故事详细信息。
I have used, Person.find().populate("stories");
我用过Person.find().populate("stories");
But it throws error, 但这会引发错误,
{
[CastError: Cast to ObjectId failed
for value "26747261"
at path "_id"
]
message: 'Cast to ObjectId failed for value "26747261" at path "_id"',
name: 'CastError',
kind: 'ObjectId',
value: 26747261,
path: '_id',
reason: undefined
}
Please help. 请帮忙。
The reason you are getting the CastError is that you are not storing a list of story ids as you intended in the Person schema: 出现CastError的原因是您没有按照Person模式中的预期存储故事ID列表:
var personSchema = Schema({
...
stories : { type: Array, ref: 'Story' }
});
Instead you should change it to: 相反,您应该将其更改为:
var personSchema = Schema({
...
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
Also note the following (from Mongoose's documentation on population) 另请注意以下(从猫鼬的文档人口)
ObjectId, Number, String, and Buffer are valid for use as refs. ObjectId,Number,String和Buffer有效用作引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.