【问题标题】:Mongoose doesn't update my document if I have no callback function如果我没有回调函数,Mongoose 不会更新我的文档
【发布时间】:2013-01-30 10:34:00
【问题描述】:

这是我的模型:

var UserSchema = new Schema({
    username: { type: String, unique: true, index: true },
    url: { type: String },
    name: { type: String },
    github_id: { type: Number },
    avatar_url: { type: String },
    location: { type: String },
    email: { type: String },
    blog: { type: String },
    public_repos: { type: Number },
    public_gists: { type: Number },
    last_github_sync: { type: Date },
    created_at: { type: Date, default: Date.now }
});

我尝试使用findOneAndUpdate 函数更新我的文档:

不起作用:

User.findOneAndUpdate({ github_id: 1 }, { last_github_sync: new Date() }, {});

不起作用:

User.findOneAndUpdate({ github_id: 1 }, { last_github_sync: new Date() });

作品:

User.findOneAndUpdate({ github_id: 1 }, { last_github_sync: new Date() }, {}, function (err, numberAffected, raw) { });

我的意思是我应该绑定回调函数来使更新操作工作,但我不需要那个回调函数,我的代码有什么问题?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    查看findOneAndUpdatedocumentation中的示例:

    A.findOneAndUpdate(conditions, update, options, callback) // executes
    A.findOneAndUpdate(conditions, update, options)  // returns Query
    A.findOneAndUpdate(conditions, update, callback) // executes
    A.findOneAndUpdate(conditions, update)           // returns Query
    A.findOneAndUpdate()                             // returns Query
    

    如果您不提供回调,它会返回一个Query 对象,您必须调用exec() 才能执行更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-10
      • 2016-03-12
      • 2017-03-17
      • 2015-07-12
      • 2013-08-06
      • 2021-03-21
      • 1970-01-01
      • 2020-07-11
      相关资源
      最近更新 更多