为什么我不能增加这个属性?

时间:2017-12-10 12:44:11

标签: node.js database mongodb mongoose nosql

我想在NodeJS中创建一个增加子文档属性的路由,但我不知道该怎么做,而我现在的做法似乎不起作用。

blogPost模型

  const BlogPostSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  rating: Number,
  title: String,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  board: {type: Schema.Types.ObjectId, ref: 'board'},
  comments: [commentSchema]
});

const BlogPost = mongoose.model('blogPost', BlogPostSchema);

module.exports = BlogPost;

评论架构

const CommentSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  rating: Number
});

module.exports = CommentSchema;

NodeJS路线

routes.put('/blogPosts/:id/comment/:idm', function(req, res) {
    const blogPostId = req.param('id');
    const commentId = req.param('idm');

    BlogPost.findById(blogPostId)
        .then((blogPost) => {
          blogPost.comments.findByIdAndUpdate({_id: commentId}, {$inc: {rating: 1}});
        })
        .then((blogPost) => res.status(200).json({
        'status': 'Comment rating is increased.'
    }))
    .catch((error) => res.status(400).json(error))
});

这是回复Postman

感谢所有帮助。

1 个答案:

答案 0 :(得分:0)

这个承诺还没有得到解决,所以你可以做的是使用异步等待函数或JavaScript生成器,这将使客户端等到评级增加并且结果json被发送。

这是关于async-awaitgenerators的教程。