【问题标题】:Mongoose findOneAndUpdate proper use猫鼬 findOneAndUpdate 正确使用
【发布时间】:2016-05-06 04:10:15
【问题描述】:

我正在尝试使用 Express 和 Mongoose 自学 Node.js。

我正在处理的网站部分是一个投票系统,除了跟踪用户投票的一小部分(尽管相当重要的部分)之外,我已经完成了所有工作......

我有一个包含此代码的投票处理程序

pollVote : function(req, res, next) { //needs poll name, user, and their vote
    Polls.findOne({'active' : true},  function(err, poll) {
        if(err)
            throw err;

        if(poll) {
            if(poll.users.indexOf(req.user.userData.username) > -1) {
                req.polls.response = "You have already voted...";
                next();
            } else {
                var index = poll.labels.indexOf(req.polls.vote);
                var voteIndex = {};
                voteIndex['votes.' + index];
                var query = {'active' : true};
                var update = {$inc : {voteIndex : 1}, $push : {users : req.user.userData.username}};
                var options = {};
                Polls.findOneAndUpdate(query, update, options, function(err, poll){
                    if(err)
                        throw err;
                    req.polls.response = "Voted";
                    next();
                });


            }           
        } else {
            req.polls.response = "FAILED";
            next();
        }
    });
},

prepVote : function(req, res, next) {
    var data = req.body.stringData;
    data = data.split(',');
    var name = data[0];
    var vote = data[1];
    req.polls = {
        name : name,
        vote : vote,
        response : ""
    }
    next();

},

我的路由器这样调用它

app.post('/poll-vote', requestedOn, isLoggedIn, pollHandler.prepVote, pollHandler.pollVote, function(req, res) {
    res.send(req.polls.response);
});

我的 Mongoose Schema 是这样的

var mongoose = require('mongoose');

var pollSchema = mongoose.Schema({
name        : String,
active      : Boolean,
users       : [String],
labels      : [String], 
votes       : [Number],
answerDesc  : [String],
created     : Date,
deactivated : Date

});

module.exports = mongoose.model('Polls', pollSchema);

当我尝试投票时,我得到一个 MongoError 说明“'$inc' 为空。您必须指定一个像这样的字段:{$inc: {: ...}} 但是这就是我设置它的方式是吗?

我在这里和 Mongoose API 上搜索了很多不同的条目。我最初试图通过保存来做到这一点,但它没有保存我的更改。

我来自 SQL 背景,所以这个基于文档的数据库系统有点令人困惑。谢谢

【问题讨论】:

  • 您的意思是增加votes 而不是voteIndexvoteIndex 不在 Poll 模型的架构中。
  • @rolfmyeggo voteIndex 是我设置为 ['votes.' 的变量。 + index] 其中 index 是用户在投票中选择的标签的 indexOf。
  • $inc 用于在找到的文档上增加数据库中的字段。这是findOneAndUpdate 的功能。 :)
  • 是的,但是我如何指示数组“投票”的正确元素我不知道在执行时要增加哪个元素,我试图将它与标签数组中的元素匹配以便我以后可以生成准确的结果。
  • 我明白了。尝试将其添加为字符串,不使用 Object 表示法。

标签: node.js express mongoose


【解决方案1】:

如果您想增加 votes 字段中的子字段,则可以使用 MongoDB 指定的 dot notation

$inc

$inc 运算符将字段增加一个指定的值,并具有以下形式:

{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

要在嵌入文档或数组中指定 a,请使用 点表示法

请参阅此示例,了解如何在$inc 中使用点符号

db.products.update(
   { sku: "abc123" },
   { $inc: { quantity: -2, "metrics.orders": 1 } }
)

您的问题在于您如何指定点符号。你不能使用var voteIndex = 'votes.' + index,因为你不能在对象文字语法中使用除常量字符串之外的任何东西。

你有两个选择:

1) 对于包含部分EMCAScript 2015 (ES6) 规范的较新版本的Node.js,您可以使用[exp]: value 语法,如下所示。

var update = {$inc : {["votes.${index}"] : 1}, $push : {users : req.user.userData.username}};

2) 在旧版本的Node.js 中,您可以先创建Object,然后再将其与$inc 一起使用。

var index = poll.labels.indexOf(req.polls.vote);
var voteIndex = {};
voteIndex['votes.' + index] = 1;
var query = {'active' : true};
var update = {$inc : voteIndex, $push : {users : req.user.userData.username}};

【讨论】:

  • 呸呸呸呸呸……我做出了改变,看起来它即将开始工作了。看起来像 {$inc: {["votes.${index}"] : 1} 现在但是我得到错误:不能使用部分 (votes of votes.${index}) 来遍历元素 ({votes: [ 0, 0]})
  • 第二个做到了!虽然我在三周前下载了 node.js,但奇怪的是它已经过时了?非常感谢您的帮助和耐心
猜你喜欢
  • 2021-09-25
  • 2017-10-05
  • 2018-07-15
  • 2020-11-13
  • 2013-06-19
  • 2013-02-13
  • 1970-01-01
  • 2022-01-22
  • 2019-11-10
相关资源
最近更新 更多