27

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?

2 Answers 2

37

As of Mongoose 4+, do not forget to set new: true along with upsert or you will get the old document as a return value, not the updated one.

This is quite tricky especially when the request creates a document, as if you do not specify new: true, you receive a null document (there was no existing doc), but no error.

    var myObj = ...;
    collection.findOneAndUpdate(
    {uniqueAttr: myObj.uniqueAttr},
    myObj,
    {upsert: true, new: true},
    function(...) {...}
1
  • 3
    You saved my day! Was banging my head after migrating to latest version of mongoose Commented Nov 7, 2016 at 8:06
29

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(){
     ...
});
2
  • 6
    It's a bit weird: I wish to simply create a document if it doesn't exist, so conditions and update are the same, but this does fix the prob. Commented Aug 4, 2014 at 10:44
  • If you want to create an object then use insert or create. Update is for finding an object that already exists, and then changing its value. Commented Dec 21, 2015 at 8:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.