gpt4 book ai didi

node.js - Mongoose 协会

转载 作者:搜寻专家 更新时间:2023-10-31 23:23:34 26 4
gpt4 key购买 nike

我是新手。我正在尝试加入不同的集合以获取一些数据。我能够获取帖子创建者和喜欢的信息,但是如何使用 mongoose 中的关联获取包含他们的评论和评论者信息的帖子?

用户模式

 const userSchema = mongoose.Schema({
username: {
type: String,
minlength: [6, 'Minimum length of username must be 6 characters'],
trim: true,
lowercase: true,
required: true,
unique: true
},
email: {
type: String,
minlength: [6, 'Minimum length of email must be 6 characters'],
trim: true,
unique: true
},
password: {
type: String,
minlength: [6, 'Minimum length of password must be 6 characters'],
required: true
},
tokens: [{
access: {
type: String
},
token: {
type: String
}
}],
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'post'
}]
}, {
timestamps: true
});

POST 架构

 const postSchema = mongoose.Schema({
title: {
type: String,
trim: true,
required: true
},
body: {
type: String,
trim: true,
required: true
},
_creator: {
type: ObjectId,
ref: 'user'
},
comments: [{
type: ObjectId,
ref: 'comment'
}],
likes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}]
}, {
timestamps: true
});

评论架构

 const commentSchema = mongoose.Schema({
title: {
type: String,
trim: true
},
_creator: {
type: ObjectId,
ref: 'user'
},
_post: {
type: ObjectId,
ref: 'post'
}
}, {
timestamps: true
});

// get posts from all users
postRoutes.get('/', authMiddleware, async(req, res) => {
try {
const user = req.user;
const posts = await Post.find({})
.populate('_creator likes comments')
.sort({
createdAt: -1
})
.limit(1);

return res.send(posts);

} catch (e) {
return res.status(400).send(e);
}
});

我只得到评论 ID,但我想要评论及其信息。我究竟做错了什么? json_object_image

最佳答案

您正在寻找 Mongoose populate这是文档的链接 http://mongoosejs.com/docs/populate.html

关于node.js - Mongoose 协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44777959/

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