I can't understand why this simple code fails in a very strange way: after calling the mongoose method, I get no messages, and program terminates, without any action on db.
This is the code:
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);
});
The output is just:
saving...
Then program terminates, without adding or modifying any data on db.
This is the model, if it can help:
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);
I'm sure I'm missing something obvious, but... :-(
Any clue?