【发布时间】:2020-09-29 10:29:14
【问题描述】:
这是我的模型:
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({ "options.uid": optionId }, { $inc: { "options.$.votes": 1 }, { new: true } })
标签: javascript node.js mongodb mongoose mongoose-schema