Rabbit mongoose, part 2: faster update

My previous post gives tips to get data faster. In this post I give so tips to update data faster than with the simple save method.

♻ The basic save method

Here is the schema I gonna use:

const UserSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
});

Typicall code to update such data using Id is:

userModel.findById('5767d3add9340ba8102e9f4b').then(
    (user) => {
        user.lastName = newName;
        user.save((err, updatedUser) => {
            ...
        });
    }
);

(To keep example simple I don’t show error management)

This code has two optimization flaws:

  • It reads the user prior to the update
  • It use mongoose object

♻ A faster approach

userModel.findByIdAndUpdate(
    '5767d3add9340ba8102e9f4b',
    {'lastName': newName},
    {new: true, upsert: false}
).lean().then((modifiedUser) => {
  ...
});

Here, only one request (no prior reading request) and no mongoose object. This request is longer to write, but way faster to execute. For sure, one may modify something without knowing the id: mongoose offers a bunch of findAndModify functions: I invite you to digg into mongoose API.

♻ Precaution

Mongoose manages a version field names __v. It automatically increments it each time a document is updated. Mongoose uses this to detect concurrent update. When one uses a method coming from mongodb driver and not from mongoose itself the __v is not used. When using non-mongoose methods, I always manage __v in my requests:

userModel.findByIdAndUpdate(
    '5767d3add9340ba8102e9f4b',
    {$set:{'lastName': newName}, $inc:{'__v':1}},
    {new: true, upsert: false}
).lean().then((modifiedUser) => {
  ...
});

That way my code keep a consistent behavior and have no trouble when I use a mix of mongoose and non-mongoose fonction.

 


 

This conclude my series about Mongoose. I hope this will help you to write faster code.

 

See you and have a nice code 🙋