这是我的模型。
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。
对于1层嵌套,不需要使用 arrayFilters
所以这个应该可以。
Poll.findOneAndUpdate({ _id: yourId, "options.uid": optionId }, { $inc: { "options.$.votes": 1 }, { new: true } })
请你试试这段代码
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);
}
}
);