made_in_india
made_in_india

Reputation: 2279

mongoose findOneandUpdate running twice inside findOne

I am using async eachSeries and updating the document when it is present. Here is the sample code.

let a = [ 
 { user_name: "foo" } 
];
async.eachSeries(a, (doc, done) => {

    Foo.findOne(doc).lean(true).exec((err, doc) => {

        if (err) return done(err);
        Foo.findOneAndUpdate(a, {
                user_last: "bar"
            }, {
                upsert: true,
                new: true
            },
            (err, doc) => {
                if (err) return done(err);
                return done(doc);
            });
    });
}, (err) => {
    console.log(completed);
});

sometime even the array a has one element , the findOneAndUpdate function is running twice in a single iteration. I am using node v6.10 and mongoose. It not happening all the time.

Is any one has encountered the similar problem.

Upvotes: 0

Views: 652

Answers (1)

Mikey
Mikey

Reputation: 6766

You could simplify your code like

let arr = [ 
    { user_name: "foo" } 
];

async.eachSeries(arr, (query, done) => {
    // note the removal of lean() as we want a document to use .save()
    Foo.findOne(query).exec((err, doc) => {
        if (err) 
            return done(err);
        // if no document is found, judging by your code you want to create a new document
        if (!doc) {
            doc = new Foo();
        }
        // at this point you will have an existing or new document
        doc.user_last = "bar";
        doc.save(done);
    });
}, (err) => {
    if (err)
        console.log(err);
    else
        console.log('completed');
});

Upvotes: 1

Related Questions