Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clone the mongoose query object in javascript

I am facing the problem of clone of the mongoose query object .Javascript the copy the one object into another object by call-by-ref but in my project there is scenario i need to copy one object into another object by call-by-value.

    var query=domain.User.find({
            deleted: false,
            role: role
        })

var query1=query;

I have the scenario change in the query object is not reflected in query1. I google and try so many way to clone the object but it does't work.The query object is used in another function for pagination and query1 object is used for count query.

1.I used to Object.clone(query1) error Object.clone is not function 2.I used Object.assign(query1) but it does't works fine. 3.I used other so many ways can anybody help me to sort this problem

like image 675
Himanshu Goyal Avatar asked Apr 21 '16 04:04

Himanshu Goyal


2 Answers

you are trying to clone a cursor, but it is not the right approach, you probably just need to create another

like this:

var buildQuery = function() {
  return domain.User.find({
    deleted: false,
    role: role
  });
};

var query = buildQuery();
var query1 = buildQuery();
like image 54
Boris Chernysh Avatar answered Sep 20 '22 18:09

Boris Chernysh


Alternative solution using merge method:

const query = domain.User.find({
  deleted: false,
  role: role
}).skip(10).limit(10)

const countQuery = query.model.find().merge(query).skip(0).limit(0)

const [users, count] = await Promise.all([query, countQuery.count()])
like image 36
Sergii Stotskyi Avatar answered Sep 19 '22 18:09

Sergii Stotskyi