【发布时间】: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