无法使用mongoose更新MongoDB

时间:2015-03-04 00:10:35

标签: node.js mongodb mongoose

我正在尝试使用de node模块mongoose从我的数据库更新集合。问题在于$set更新。这是我的代码:

// Update a user
app.patch('/user/:user_id', passport.authenticate('bearer', { session: false }),
    function (req, res) {
        var conditions  = { _id: new ObjectId(req.params.user_id)},
            updateObj   = { $set: req.body }; // {email : "bob@example.com", username: "bob"}

        User.update(conditions, updateObj, function callback (err, numAffected, rawResponse) {
            if (err) {
                res.send(err);
                return;
            }
            // numAffected is the number of updated documents
            if (numAffected == 0) {
                res.json({ message: 'No user affected'});
                return;
            }

            res.json({ message: 'User updated'});
        });

});

如果我更新现有密钥,例如email,则会更新。但是,如果我想添加新密钥,numAffected始终为0而rawResponseundefined

知道会发生什么事吗?

修改

这是我的Schema

var userSchema = mongoose.Schema({
  email     : String,
  username  : String,
  password  : String
});

2 个答案:

答案 0 :(得分:0)

要在文档中设置多个字段,您必须在配置中设置 Multi 选项,否则Mongoose将忽略该延续,并且只更新第一个doc。

来自文档:

var conditions = { name: 'borne' }
  , update = { $inc: { visits: 1 }}
  , options = { multi: true };

Model.update(conditions, update, options, callback);

function callback (err, numAffected) {
  // numAffected is the number of updated documents
});

另一个注意事项:numAffected应按预期返回,但我无法在其网站上找到有关原始响应的任何文档,但它也应按预期返回。你知道这方面的任何文件吗?

答案 1 :(得分:0)

我认为这是您真正希望mongoose更新用户的电子邮件和用户名。

app.patch('/user/:user_id', passport.authenticate('bearer', { session: false }),
    function (req, res) {

    User.findOneAndUpdate({_id: req.params.user_id},
        {  
            $set: {
                username: req.body.username,
                email: req.body.email
            }
        }, function(err, user) {
            if (err)
                res.send(err);

            if (user) {
                res.json({message: 'User updated'});
            } else {
                res.json({message: 'User does not exist'});
            }
        });
});