Mongoose更新没有回调 [英] Mongoose update without callback

查看:127
本文介绍了Mongoose更新没有回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var mongoose = require('mongoose'); 

var userSchema = new mongoose.Schema({
email:String,
password:String,
profile:{
name:String,
surname:String,
照片:String
},
stats:{
lastLogin:{type:Date,default:Date.now},
loginCount:数字,
lastIP:String
},
source:String,
deleted:Boolean,
dateCreated:{type:Date,default:Date.now}
});

mongoose.model('User',userSchema);

当我执行此更新时,它仅在定义回调时有效,否则它只是执行但没有值在数据库中更改:

  User.update({email:'foo@bar.com'},{$ inc :{'stats.loginCount':1}}); 

这样做:

  User.update({email:'foo@bar.com'},{$ inc:{'stats.loginCount':1}},function(){}); 

这是一个错误?我没有在文档中看到回调是必需的,但是这是奇怪的要求这个...我想我在这里缺少一些。



注意:我匹配通过电子邮件进行测试建议,我在NodeJS v0.8.17中使用了一个简单的Express v3.0.6安装程序中的mongoose v3.5.4。



提前感谢。 >

解决方案

使用mongoose调用更新的正确方法如下:

  User.update(query,update).exec(callback); 

这样你就可以跳过回调

  User.update(查询,更新).exec(); 

当您致电

  User.update(查询,更新)

它返回一个查询对象



这是非常有用的当您查询数据库时,因为在执行之前可以使用查询对象进行操作。例如,您可以指定 限制 ,您的查找查询:

  User.find查询).limit(12).exec(回调); 

更新使用相同的机制,不太有用。


I have a typical schema and model:

var mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
    email: String,
    password: String,
    profile: {
        name: String,
        surname: String,
        photo: String
    },
    stats: {
        lastLogin: { type: Date, default: Date.now },
        loginCount: Number,
        lastIP: String
    },
    source: String,
    deleted: Boolean,
    dateCreated: { type: Date, default: Date.now }
});

mongoose.model('User', userSchema);

When I perform this update, it only works if I define the callback, else it simply executes but no value is changed in the database:

User.update({email:'foo@bar.com'}, {$inc: {'stats.loginCount': 1}});

This works:

User.update({email:'foo@bar.com'}, {$inc: {'stats.loginCount': 1}}, function() {});

Is this a bug? I don't see in the documentation if the callback is required but it's strange to require this… I think i'm missing something here.

Notes: I'm matching by email for testing proposes, I'm using mongoose v3.5.4 in NodeJS v0.8.17 with a simple Express v3.0.6 setup.

Thanks in advance.

解决方案

The right way to call update with mongoose is the following:

User.update(query, update).exec(callback);

This way you will be able to skip callback:

User.update(query, update).exec();

When you calls

User.update(query, update)

it returns a query object.

It's very useful when you querying your database, because you can manipulate with query object before executing it. For example, you can specify a limit for your find query:

User.find(query).limit(12).exec(callback);

Update uses the same mechanism, though its not so useful there.

这篇关于Mongoose更新没有回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆