【问题标题】:update Mongoose document without Model在没有模型的情况下更新 Mongoose 文档
【发布时间】:2015-11-29 11:54:28
【问题描述】:

是否可以不使用模型直接更新 mongoose 对象?

我试过这段代码:

var user = new User();
//setting some user properties
//...
user.save(); //works

在单独的电话中我这样做:

user.update(function(error, result){
  //the update doesn't happend, but no error
  //result = [ok=1,nModified=0,n=1]
});

所以这种方法不会抛出异常并且没有错误。但它也不起作用。

当我向 google 询问如何使用 mongoose 更新文档时 我总能找到类似的方法

UserModel.update({ /*selector*/ }, {$set: { /**/ }}, function(error, result){/*...*/});

我可以用这种方法保存我的示例“用户”对象。这样就行了。

但我想知道是否也支持我直接保存到文档/对象的方法?那我做错了吗?或者这种更新文档的方式是 mongoose 不支持的?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你没有更新任何东西

    user.update(function(error, result){
     //the update doesn't happend, but no error
     //result = [ok=1,nModified=0,n=1]
    });
    

    这就是为什么在您看来它不起作用。发生的情况是您提供 undefined 选择器和 undefined 更新 ($set)。

    试试user.update({}, {$set:{ ... }}function(error, result){ ... }

    【讨论】:

    • 为什么我的回答被否决了?请给我一些解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多