Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...