【问题标题】:Why can i not increment this property?为什么我不能增加这个属性?
【发布时间】:2018-05-24 03:38:39
【问题描述】:

我想在 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的回复

感谢所有帮助。

【问题讨论】:

    标签: node.js database mongodb mongoose nosql


    【解决方案1】:

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

    这是关于async-awaitgenerators 的教程。

    【讨论】:

      猜你喜欢
      • 2010-10-25
      • 2018-05-27
      • 2014-09-22
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多