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

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

问题描述

我有一个典型的架构和模型:

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}});

这有效:

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.

注意:我正在通过电子邮件匹配测试建议,我在 NodeJS v0.8.17 中使用 mongoose v3.5.4,并通过简单的 Express v3.0.6 设置.

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.

提前致谢.

推荐答案

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

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

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

这样你就可以跳过callback:

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

当你打电话

User.update(query, update)

它返回一个查询对象.

它在查询数据库时非常有用,因为您可以在执行查询对象之前对其进行操作.例如,您可以指定一个 limitfind 查询:

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 使用相同的机制,尽管在那里不太有用.

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

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

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