【问题标题】:Mongoose: findOneAndUpdate() does not return [duplicate]猫鼬:findOneAndUpdate() 不返回 [重复]
【发布时间】:2016-06-20 00:17:43
【问题描述】:

我不明白为什么这个简单代码会以一种非常奇怪的方式失败:调用 mongoose 方法后,我没有收到任何消息,程序终止,对 db 没有任何操作。
这是代码:

var save = function(trace, callback) {
  console.log('saving...');
  Trace.findOneAndUpdate(
    { // query
      phone: trace.phone,
      link: trace.link,
    },
    { // object to save
      phone: trace.phone,
      title: trace.title,
    },
    { // options
      new: true, // return the modified document rather than the original
      upsert: true, // creates the object if it doesn't exist
      passRawResult: true // pass back mongo row result
    },
    function(err, doc, raw) { // result callback
      if (err) {
        console.log('can\'t save trace', trace.phone, trace.link, ':', err);
      } else {
        if (raw.lastErrorObject.updatedExisting) {
          console.log('trace', doc.phone, doc.link, 'updated');
        } else {
          console.log('trace', doc.phone, doc.link, 'added');
        }
        images.push(doc); // push added image
      }
      callback(err, doc); // finish image save
    }
  );
};

var trace = {
  phone: '3331234567',
  link: 'http://www.example.com/',
  title: 'title 1',
  description: 'descrption 1',
  dateOfLastSync: new Date(),
};

save(trace, function(err, doc) {
  if (err) {
    console.error('err:', err);
  }
  console.log('trace updated:', doc);
});

输出只是:

saving...

然后程序终止,不添加或修改 db 上的任何数据。

这是模型,如果有帮助的话:

var trace = new mongoose.Schema({
  phone: { type: String, required: true },
  link: String,
  title: String,
  description: String,
  dateOfLastSync: { type: Date, default: Date.now },
});
trace.index({ link: 1 }, { unique: false });
trace.index({ phone: 1 }, { unique: false });
trace.index({ link: 1, phone: 1 }, { unique: true });

module.exports = mongoose.model('Trace', trace);

我确定我遗漏了一些明显的东西,但是... :-(
有什么线索吗?

【问题讨论】:

  • 您似乎将日志记录混合到 log 对象和控制台 - 您的 log.info 是否正常工作并真正记录到控制台?
  • 是的!你是对的......更改了有问题的代码......在我的代码中,我使用了winston logger的log()......不幸的是,这不是原因,观察到相同的行为...... :-(
  • 测试您的样本,在我的本地测试中似乎效果很好......
  • 另外注意,你查询手机,在保存的对象中设置了相同的手机号码?
  • @zangw:它在回调中打印消息并在数据库中插入数据?

标签: javascript node.js mongodb mongoose


【解决方案1】:

对不起,各位!
我刚刚发现了我的愚蠢错误:只是我没有包括“db.js”,我在其中执行mongoose.connect(...) 的东西。

我将此作为答案发布,因此更少的人会花时间在这件事上......
(虽然我不知道我没有错误的事实是否很好...... :-)

再次抱歉...

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 2020-11-13
    • 2013-02-13
    • 2021-09-25
    • 2017-10-05
    • 2018-11-18
    • 2019-11-10
    • 2015-09-15
    • 2018-07-15
    相关资源
    最近更新 更多