gpt4 book ai didi

express - Mongoose :如何使用 ObjectId 链接模型?

转载 作者:行者123 更新时间:2023-12-02 00:36:38 25 4
gpt4 key购买 nike

我正在使用 Express、Mongoose 和 Mongodb。我有两个模型,一个供用户使用,另一个供审查使用,如下所示:

var User = mongoose.Schema({
firstName: String,
lastName: String,
email: String
});
mongoose.model("User", User);

var Review = mongoose.Schema({
foodRating: Number,
serviceRating: Number,
locationRating: Number,
wouldReturn: boolean
});
mongoose.model("Review", Review);

我想以评论属于用户的方式链接这两个模型。

我阅读了有关 ObjectId 的内容,但不清楚如何实现它。我应该创建它,然后使用它,就像这样:

const MyObjectId = mongoose.Types.ObjectId;

然后覆盖我想用它链接到我的第一个模型的模型的 _id?

var User = mongoose.Schema({
firstName: String,
lastName: String,
email: String,
review: [MyObjectId] // retrieves model below from its _id:MyObjectId
});
mongoose.model("User", User);

var Review = mongoose.Schema({
_id: MyObjectId, // overriding _id with ObjectId
foodRating: Number,
serviceRating: Number,
locationRating: Number,
wouldReturn: boolean
});
mongoose.model("Review", Review);

这是正确的吗?或者我该怎么做?

最佳答案

从 Mongoose 文档中查看:http://mongoosejs.com/docs/populate.html

基本上,你想要做的是:

const MyObjectId = mongoose.Types.ObjectId;

var User = mongoose.Schema({

firstName:String,
lastName: String,
email: String,
review: [MyObjectId] // retrieves model below from its _id:MyObjectId
});

mongoose.model('User', User);

var Review = mongoose.Schema({
user: { type: MyObjectId, ref: 'User' } // overriding _id with ObjectId
foodRating: Number,
serviceRating: Number,
locationRating: Number,
wouldReturn: boolean,

});
mongoose.model('Review', Review);

完成后,用户文档中的 _id 将存储在审阅文档的用户字段中。然后你可以这样做:

Review.
findOne({ foodRating: 4 }).
populate('user').
exec((err, review) => {
if (err) return handleError(err);
console.log('The user is %s %s', review.user.firstName, review.userLastName);
// prints "The user is So-and-so"
});

关于express - Mongoose :如何使用 ObjectId 链接模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49245049/

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