0

I have one array which has document ids.:

var ids = [ '5b3c7db4c079dc17dc75fc26', '5b3c7db4c079dc17dc75fc28' ]

I have one collection called Machines with documents inside. enter image description here

I am trying to get documents from Machines collection using ids which are in my array.

Machines.find({ _id : { $in : ids } }).fetch();

this returns []

3 Answers 3

3

Try this:

var ids = [ ObjectId("5b3c7db4c079dc17dc75fc26"), ObjectId("5b3c7db4c079dc17dc75fc28") ]

Because Mongodb stores id as ObjectId("Actual Id")

Sign up to request clarification or add additional context in comments.

Comments

1

Your

var ids = [ '5b3c7db4c079dc17dc75fc26', '5b3c7db4c079dc17dc75fc28' ]

looks like they're either hex string or native MongoDB BSON type ObjectID.

Try this for Meteor's Mongo:

import { Mongo } from 'meteor/mongo';

const ids = [
  new Mongo.ObjectID('5b3c7db4c079dc17dc75fc26'),
  new Mongo.ObjectID('5b3c7db4c079dc17dc75fc28'),
]

Machines.find({ _id : { $in : ids } }).fetch();

For better syntax, use .map() to get a new array of Mongo.ObjectID type IDs.

import { Mongo } from 'meteor/mongo';

const ids = ['5b3c7db4c079dc17dc75fc26', '5b3c7db4c079dc17dc75fc28', ...];
const mongoIds = ids.map(id => new Mongo.ObjectID(id));

Machines.find({ _id : { $in : mongoIds } }).fetch();

// if ids were ObjectIDs instead of literal strings
const objectIdToMongoIds = ids.map(id => new Mongo.ObjectID(id.toString()));
Machines.find({ _id: { $in: objectIdToMongoIds } });

Comments

0

You can also try Machine.findById(req.params.id, () => {}

Comments

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.