简体   繁体   English

如何使用mongoose在mongodb的用户集合中查询一组用户?

[英]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. 我的节点和mongodb应用程序中注册了一些用户(以及他们的联系电话)。 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. 您可以使用$in运算符。 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 . 这是一个如何做的示例ii假设您使用的是猫鼬,并且具有带number属性和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. 基本上,此函数将循环遍历联系人列表数组,并在用户集合中找到该联系人为no的任何用户,并返回诺言。 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. 所有的promise将被推送到一个数组中,并且仅当所有异步操作完成导致成功或错误时,promise才会被解析。

// 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)); 
   })
 })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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