Mongoose findOneAndUpdate and upsert returns no er

2019-01-23 13:14发布

问题:

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?

回答1:

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:

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(...) {...}