简体   繁体   中英

How to query for an array of users in my users collection in mongodb using mongoose?

I have a collection of some users (along with their contact numbers) registered in my node and mongodb app. Now I have an array of contact numbers. I want to get an intersection of this array and the users in my app. How to do it, since I cannot take each number and check for it's existence in the database. Any help/link would be helpful. Thanks in advance.

You can use the $in operator. It would really help if you at least provided some code, like your schemas, previous attempts etc.

Here is an example of how to do ii assuming you are using mongoose, and have a user schema with a number property and an array of numbers .

User.find({ number: { $in: numbers } })
  .then(function (docs) {
    // do something with docs here;
  })
  .catch(handleErr);

This can be done simply using promises. I am assuming you have an array of contact numbers and a collection Users which has field contact number. The below function will get you the list of all the Users with contact numbers listed in the array. I am assuming that the User model is available and the contact array is being passed as a function argument. Basically this function will loop through the contact list array and find any user with that contact no in the user collection and return a promise. All the promises are being pushed into an array and the promise will be resolved only when all the async operations have completed resulting in either success or error.

// import User from User-model-defition
function getUsersByContact(contactArr) {
 return new Promise((resolve, reject) => {
  const data = [];
  const errors = [];
  contactArr.map(id => {
      User.findOne({ contact_no : id })
     .then(response => {
        if (response.user) { //checking if the response actually contains a user object
        data.push(response.user);
      } else {
        errors.push(response.error);
      }
      if (contactArr.length === data.length + errors.length) {
       //this makes sure that the promise will be resolved only when all the promises have been resolved
       resolve({ data, errors });
     }
     })
    .catch(error => reject(error)); 
   })
 })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM