0

How to use multi query like find , update , insert , delete in one service on mongodb

I can query this below

router.get('/userlist', function(req, res) {

  User.find({},function (err, docs) {
    res.json(docs);
  });
});

but i want to query like this is an error

router.get('/userlist', function(req, res) {
  var data = array();
  User.find({},function (err, docs) {
     data['data1'] = docs
  })
  Content.find({},function (err, docs) {
    data['data2']  = docs
  })
  res.json(docs)
});

Can anyone help me or It is possible to use query like this? Thank you

1
  • in your response you pass res.json(docs) not valid because you push the data in data array. so pass the response res.json(data) Commented Feb 13, 2020 at 6:07

3 Answers 3

1

You can use async await to run multiple mongo queries inside a function like below:

router.get('/userlist', async function(req, res) {
   var data = array();
   try{
       //first query
       let user_data = await User.find({}).exec();
       data['data1'] = user_data;

       //second query
       let content_data = await Content.find({}).exec();
       data['data2']  = content_data;

       return res.status(200).json(data)
   }
   catch(err){
       return res.status(400).json({err})
   }
});
Sign up to request clarification or add additional context in comments.

Comments

0

My question is what is stopping you? Yes, you can do this. I did those kinds of works.

There remain two points.

If you need to perform multiple queries, based on the response of the previous query, you can use async/await or promises. If you don't wanna try those, there is still a way. You can check the response of the previous query, make conditions, and if right, execute the seconde one. And thus you can make a chain of queries.

And if you don't need to rely on the responses, do whatever you want. There is nothing wrong...

Happy Coding!

Comments

0

You have to wait for your database call response. So, You can use promise for this. MDN: Promise Make promise of database call and resolve that after you got data from database. Promise.all will wait until your both the promises resolved. MDN: Promise.all()

router.get('/userlist', function(req, res) {
  var data = [];
  let promise1 =  new Promise((resolve, reject) => {
    User.find({},function (err, docs) {
      data['data1'] = docs;
      resolve();
    })
  });

  let promise2 =  new Promise((resolve, reject) => {
    Content.find({},function (err, docs) {
      data['data2']  = docs
    })
  });

  Promise.all([promise1, promise2]).then(result => res.json(docs))
});

1 Comment

I send my response like this, res.type('json'); res.jsonp(data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.