尝试填充父对象的数组,但是这样做很麻烦

时间:2019-09-12 13:29:18

标签: node.js mongoose

因此,我有一些用户/帖子/评论,我想确保在对帖子发表评论时,该用户的评论数组已更新为包含他们刚刚发表的评论。我尝试四处搜索,似乎最好的方法是使用猫鼬的填充物,但似乎不起作用。我仍然是Mongoose的初学者,所以任何帮助或指导将不胜感激。谢谢!

我尝试过这样的事情:

   comment.save((err) => { //save the comment
      if (err) return next(err);
      res.status(200).json(comment);
    });


User.find({username: username})
      .exec((err, user) => {
        user.comments.push(comment); // says comments is undefined, but should be []
        user.comment_count++; // also, is there a way to set comment_count equal to the length of the comments array? Should I use .pre()?
        user.save(() => {
          if (err) return next(err);  
        });
      });

这给我一个错误,例如无法推送到users.comments(未定义)。

这是我的模式:

const PostSchema = new Schema({
  postedBy: {
    type: String,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  createdAt: {type: Date, default: Date.now},
  comments: [{ type: Schema.Types.ObjectId, ref: 'CommentSchema' }],
  likedBy: [User]
});

const CommentSchema = new Schema({
  parentID: { type: String, 
    required: true,
  },
  postedBy: {
    type: User,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  createdAt: {type: Date, default: Date.now},
  editedAt: {type: Date, default: Date.now},
  likedBy: [User],
});
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
  comments: {
    type: [{ type: Schema.Types.ObjectId, ref: 'CommentSchema' }],
    default: [],
  },
  comment_count: { // how do I set this equal to the length of the comments array?
    type: Number,
    default: 0,
  },
  posts: {
    type: [{ type: Schema.Types.ObjectId, ref: 'PostSchema' }],
    default: [],
  },
  post_count: { // how do I set this equal to the length of the posts array?
    type: Number,
    default: 0,
  },
});

我也尝试过人口:

const comment = new Comment({
      parentID,
      postedBy,
      content,
    });

   comment.save((err) => { //save the comment
      if (err) return next(err);
      res.status(200).json(comment);
    });


User.find({ username: username })
    .populate('comments')
    .exec((err, user) => {
         if(err) next(err);
         console.log(user); // returns undefined for some reason
                            // also not sure what to do in this function...
       });

这给了我一个错误,例如“将标头发送到客户端后无法设置标头。”

1 个答案:

答案 0 :(得分:0)

首先阅读有关诺言和回叫如何工作的更多信息。 快速修复是。

 comment.save((err) => { //save the comment
  if (err) return next(err);

User.find({username: username})
      .exec((err, user) => {
       if (err1) return next(err1); 
       res.status(200).json(user);
      });
});

“将标头发送到客户端后无法设置标头。” 错误,因为您已经发送了响应。

 res.status(200).json(comment);