【问题标题】:How do I increment a property of a subdocument in Mongoose?如何在 Mongoose 中增加子文档的属性?
【发布时间】:2018-05-23 21:48:22
【问题描述】:

我正在使用 Mongoose 在 NodeJS 中创建一个路由,它会增加对象子文档的评级。我将在下面发布模型和路线代码。当我在 Postman 中执行查询时,我得到一个空的 json 对象和一个 400 错误。这意味着在查询中的某个地方我做错了什么。

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的回复

感谢所有帮助。

【问题讨论】:

  • findByIdAndUpdate() 方法似乎只需要第一个参数的 id,只是方法名称。你确定它不应该是blogPost.comments.findByIdAndUpdate(commentId, {$inc: {rating: 1}});吗?或者,您可以改用findOneAndUpdate() 方法。文档似乎同意:mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
  • 几个问题/澄清: 1. req.params 而不是 req.param 2. blogPost.comments.findByIdAndUpdate 这是有效的吗?我猜是因为我以前从来没有这样工作过。 3. 正如 B. Fleming 所说,findByIdAndUpdateid 作为其第一个参数,您不需要将其作为查询放入。

标签: node.js database mongodb api mongoose


【解决方案1】:

这是错误:

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

应该是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-27
    • 2015-08-08
    • 2015-08-24
    • 2019-05-27
    • 2018-10-13
    • 2015-11-08
    • 2013-01-15
    • 2015-03-23
    相关资源
    最近更新 更多