How to Re-Use MongoDB Queries

Suppose I have a mongodb query as such :


I want to use this query across many functions and I want to reuse it and avoid writing the same query over and over again.

1 answer

  • answered 2018-12-05 20:14 Nitish Thakrar

    You can re-use query only if you provide condition and object data in function. Check below code it may help you to get the same result.

    This will be your model function.

    user.updateUser = function (conditon, updateData, callback) {
      userModel.update(conditon, updateData).exec(callback);

    You can call this function like as below.

    userModel.updateUser({_id: userId, name:name},{$set:{data:data}}, (err, result) => {
        console.log(err, result);