首页 > 解决方案 > 使用月光在数组中增加对象时遇到问题

问题描述

所以我有一个看起来像这样的对象

{"_id":"5fb07ab6215679200cef0eb1","user":{"_id":"5fb07437538fcd2870e21a8e","email":"example@example.com","id":"5fb07437538fcd2870e21a8e"},"question":"question?","answers":[{"_id":"5fb07ab6215679200cef0eb2","answer":"Yes","votes":0}],"voters":[],"createdAt":"2020-11-15T00:47:50.156Z","updatedAt":"2020-11-15T00:47:50.156Z","__v":0,"id":"5fb07ab6215679200cef0eb1"}

我正在尝试使用 findOneAndUpdate 通过此函数增加投票变量

export const castVote = async (id, answersid) =>
  Poll.findOneAndUpdate(
    { id, 'answers._id': answersid },
    { $inc: { 'answers.$.votes': 1 } }
  );

据我所见,调用castVote("5fb07ab6215679200cef0eb1", "5fb07ab6215679200cef0eb2")不会使服务器崩溃并且不会返回任何错误,但是答案对象中的投票变量不会增加,所以一定有问题。我在这里有什么明显的遗漏吗?

标签: node.jsmongodbmongoose

解决方案


got it working by simply dropping the id field which i guess i enough since they're uniquely created


推荐阅读