gpt4 book ai didi

javascript - Mongoose Node Js 连接两个集合

转载 作者:行者123 更新时间:2023-12-03 06:42:27 26 4
gpt4 key购买 nike

我是 MEAN Stack 的新手,正在使用 Node Js 开发应用程序。

我有两个集合,

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);

Person 架构中,storiesstory_id 的列表,它是一个值数组。我需要列出所有人员数据及其故事详细信息。

我用过,Person.find().populate("stories");
但它会抛出错误,

{
[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
}

请帮忙。

最佳答案

您收到 CastError 的原因是您没有按照预期在 Person 架构中存储故事 ID 列表:

 var personSchema = Schema({
...
stories : { type: Array, ref: 'Story' }
});

相反,您应该将其更改为:

 var personSchema = Schema({
...
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

另请注意以下内容(来自 Mongoose 关于人口的 documentation)

ObjectId, Number, String, and Buffer are valid for use as refs.

关于javascript - Mongoose Node Js 连接两个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37895827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com