Mongoose 按 id 递增嵌套数组

Mongoose increment nested array by id

这是我的模型:

const mongoose = require("mongoose");
const shortid = require("shortid");
const { v4: uuidv4 } = require("uuid");

const PollSchema = new mongoose.Schema({
  id: {
    type: String,
    default: shortid.generate
  },
  question: {
    type: String
  },
  options: [
    {
      option: {
        type: String
      },
      votes: {
        type: Number,
        default: 0
      },
      uid: {
        type: String,
        default: uuidv4
      }
    }
  ],
  created: {
    type: Date,
    default: Date.now
  }
});

module.exports = Poll = mongoose.model("poll", PollSchema);

我需要通过 uid 搜索投票并将投票数增加 1。 这是我尝试过的方法,但没有用:

Poll.findOneAndUpdate(
  { options: { $elemMatch: { uid: optionId } } },
  { $inc: { "options.$.votes": 1 } },
  { new: true }
);

数据库中没有任何更新我不确定为什么。我提供的搜索 uid 的 var 是 optionId。

你能试试这个代码吗:

Poll.findOneAndUpdate(
  { _id: id }, //that is poll id
  {
    $inc: { [`options.$[outer].votes`]: 1 }
  },
  {
    arrayFilters: [{ "outer.uid": optionId }],
    new: true
  },
  function(err, poll) {
    if (!err) {
      console.log(poll);
    }
  }
);

对于 1 级嵌套,没有必要使用 arrayFilters,所以这应该有效:

Poll.findOneAndUpdate({ _id: yourId, "options.uid": optionId }, { $inc: { "options.$.votes": 1 }, { new: true } })