嵌套数组按id递增

问题描述 投票:0回答:1

这是我的模型。

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的变量是optionId。

javascript node.js mongodb mongoose mongoose-schema
1个回答
1
投票

对于1层嵌套,不需要使用 arrayFilters 所以这个应该可以。

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

2
投票

请你试试这段代码

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);
    }
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.