mikemaccana mikemaccana - 5 months ago 665
Node.js Question

Mongoose findOneAndUpdate and upsert returns no errs, no documents affected

I have a very minimal model:

var CompanySchema = new mongoose.Schema({
name: { type: String, required: true, unique: true },
});

var Company = mongoose.model('Company', CompanySchema)


I am attempting to add a single document if it doesn't exist. Currently, there are no documents while I test:

models.Company.findOneAndUpdate({
name: 'companyName'
}, {upsert: true}, function(err, numberAffected, raw){
console.log(err, numberAffected, raw)
})


This is using the
upsert
options from the Mongoose docs


However
err
is
null
,
numberAffected
is null. Why isn't my document updated?

Answer

in your code you are using the 3 parameter version of the method findOneAndUpdate so, according to the documentation you posted, the parameters are: A.findOneAndUpdate(conditions, update, callback).

You should use the 4th parameters version of the method to specify the upsert option.

I would like to point out that I never used the framework mongoose. Hope this helps.

Edit: Yes, in your case, conditions and update are the same. If your object is more complex then the one showed in the example, you might want to check for the _id or a "unique" (not guaranteed by MongoDB) attribute (better if it has an index on it). For example:

var myObj = ...;
collection.findOneAndUpdate({uniqueAttr: myObj.uniqueAttr}, myObj, {upsert: true}, function(){
     ...
});
Comments