简体   繁体   中英

MongoDB and nodejs, find throught list of ids

I have two collections: users:

{
  _id: ObjectId('123...'),
  docs: [
    ObjectId('512d5793abb900bf3e000002'),
    ObjectId('512d5793abb900bf3e000001')
  ]
}

docs:

{
  _id: ObjectId('512d5793abb900bf3e000002'),
  name: 'qwe',
  ...
}
{
  _id: ObjectId('512d5793abb900bf3e000001'),
  name: 'qwe2',
  ...
}

I want to get docs from ids. I try this solution , but I get this message:

{ db: { domain: null, _events: {}, _maxListeners: 10, databaseName: 'test', ...

Your message looks like a mongodb cursor returned from find by native mongodb driver .

To get actual data you should use toArray function of the cursor:

var ObjectID = require('mongodb').ObjectID;
// you shall wrap each id in ObjectID
var idsProjects = [
  ObjectID('512d5793abb900bf3e000002'),
  ObjectID('512d5793abb900bf3e000001')
];
collectionProjects.find({
  _id: { $in: idsProjects }
},{
  _id: -1, // use -1 to skip a field
  name: 1
}).toArray(function (err, docs) {
  // docs array here contains all queried docs
  if (err) throw err;
  console.log(docs);
});

But I recommend you to switch from native mongodb driver to some wrapper around it like monk .

If you care about the order of the list, the answer of Mr.Leonid may not work as expected to do.

That's because find gets the docs that have _id equals to any _ids $in the list so the output docs will be ordered by the main order of the collection itself not the order of the input list.

To solve that you can just use the normal findOne with a for loop to the list.

The code will look like:

var ObjectID = require('mongodb').ObjectID;
var idsProjects = [
  '512d5793abb900bf3e000002',
  '512d5793abb900bf3e000001'
];
let usersList = new Array();

for (let index = 0; index < idsProjects.length; index++) {
    const myID = idsProjects[index];
    
    const query = { _id: ObjectID(myID) };
    const options = {
    projection: {name: 1 };
    
    var user= await collectionProjects.findOne(query,options);
    
    usersList.push(user);
}

// that's it,
// here we have a list of users 'usersList' 
//with same order of the input ids' list.
console.log(usersList);

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