猫鼬:$inc 不工作 [英] Mongoose: $inc not working
问题描述
我不知道是什么问题,因为我读过很多例子.
I am not sure what the problem is, as I've read numerous examples.
取自我在此 StackOverFlow 中的建议(Mongoose - 在对象数组中增加一个值),我轻松地更改了 poll 的格式以适应推荐的内容.
Taken from what I was advised here in this StackOverFlow(Mongoose - Increment a value inside an array of objects), I changed the format of poll at ease to accommodate what was recommended.
所以我能够像这样创建文档格式:
So I was able to create a document format as so:
{
"_id": "584c4160b3b22e1bdad59bce",
"title": "Food",
"description": "test",
"labelOptions": {
"burger": 29,
"coffee": 44,
"pizza": 23
},
"date": "Dec 10, 2016",
"__v": 0
}
这是我目前所拥有的:
投票模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const pollData = new Schema({
title: String,
description: String,
labelOptions: {},
date: String
})
module.exports = mongoose.model('PollData', pollData)
使用 express 和 mongoose,这是我所拥有的:
Using express and mongoose, here's what I have:
app.put('/polls/:id', function(req, res){
let id = req.params.id;
let labelOption = req.query.labelOption;
let query = `labelOptions.${labelOption}`
Poll.findByIdAndUpdate(
id,
{$inc: { query: 1 } },
function(err, document){
console.log(err)
console.log(document)
}
)
})
在我的终端中,我看到 console.log(document
它收到了我正在寻找的文档,但它根本没有更新该值.
In my terminal, I see that console.log(document
it receives the document I was looking for but it does not update the value at all.
我是否正确设置了模型?还是 Mongoose 不支持模板字符串?
Am I setting up the Model correctly? Or does Mongoose does not support template strings?
***更新这是我如何创建文档的片段
***update This is snippet of how I am creating documents
let labelOptions = {}; <=== creating object literal to hold as placeholder
const title = req.body.title;
const description = req.body.description;
req.body.labelOptions.split(/,\s*/).map( prop =>{
labelOptions[prop] = 0 // set counter to default 0
})
const poll = new Poll({
title: title,
description: description,
labelOptions: labelOptions,
date: moment().format('MMM D, YYYY')
});
poll.save(function(err) {
if (err) { return next(err); }
res.json({ message : 'Poll added!'})
});
推荐答案
在互联网上进行了一些研究后,我发现了它不起作用的原因:您无法使用动态"键初始化对象.
After doing some research across the internet, I found the reason why it wasnt working: You can't initialize objects with 'dynamic' keys.
知道了这一点,这只是一个简单的初始化文字对象的解决方案:
By knowing that, it was just a simple solution to initialize an literal object as so:
let id = req.params.id;
let labelOption = req.query.labelOption;
let query = "labelOptions." + labelOption
let obj = {
[query] : 1
}
Poll.findByIdAndUpdate(
id,
{$inc: obj },
function(err, document){
console.log(err)
console.log(document)
}
)
这篇关于猫鼬:$inc 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!