如何解决Mongoose 填充数组字段的字段
我有一个收藏用户和一个收藏帖子。帖子可以有评论,这些评论存储在帖子内的数组中。我想引用用户的这些评论,所以用户应该得到他发布的帖子和他所做的评论。
当我查询 getMe() 时,我可以访问帖子,但无法访问评论。 我的问题是如何以更好的方式存储和访问评论?
我的模型看起来像
const userSchema = new Schema({
username: String,post: [
{
type: Schema.Types.ObjectId,ref: "Post",},],comments: [
type: Schema.Types.ObjectId,});
const postSchema = new Schema({
body: String,comments: [
{
body: String,postedBy: {
type: Schema.Types.ObjectId,ref: "User",user: {
type: Schema.Types.ObjectId,});
我添加帖子和评论的方式:
await User.findOneAndUpdate(
{ _id: user.id },{ $push: { post: newPost._id } }
).catch((err) => new Error(err));
await User.findOneAndUpdate(
{ _id: user.id },{ $push: { comments: lastCommendId } }
).catch((err) => new Error(err));
我想访问存储的帖子和评论的方式:
Query: {
async getMe(_,__,context) {
const userContext = checkAuth(context);
const user = await User.findOne({ _id: userContext.id }).populate(
"post"
)
.populate("comments")
return {
id: user._id,post: user.post,comments: user.comments,};
},
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。