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

时间:2021-09-15 21:04:00

I want to make a route in NodeJS which increment the property of a subdocument but I don't know how to do it and the way I am doing it now does not seem to work.

我想在NodeJS中创建一个路径,增加子文档的属性,但我不知道如何做到这一点,我现在的方式似乎不起作用。

blogPost model

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;

comment schema

评论架构

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 route

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))
});

This is the response Postman

这是邮递员的回应

All help is appreciated.

所有帮助表示赞赏。

1 个解决方案

#1


0  

Well the promise hasn't been resolved, so what you can do is use async await functions or JavaScript generators which will make the client wait till the rating is incremented and the results json is sent.

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

Here's a tutorial on async-await and generators.

这是关于async-await和generator的教程。

#1


0  

Well the promise hasn't been resolved, so what you can do is use async await functions or JavaScript generators which will make the client wait till the rating is incremented and the results json is sent.

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

Here's a tutorial on async-await and generators.

这是关于async-await和generator的教程。