Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - Find a document from collection via Mongo ObjectId

Tags:

mongodb

meteor

If you create a Mongo document directly inside Mongo and want to access this same document via Meteor, what is the best way to accomplish this task?

I am getting undefined result when I attempt to access.

If you create a new document from Meteor it does not prefix the id with ObjectId("").

Any help would be greatly appreciated.

I want to simply find exact document by exact ObjectId.

like image 809
jremi Avatar asked Jul 01 '14 17:07

jremi


People also ask

What is the use of ObjectID in MongoDB?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated during the creation of any document. Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>).

How do I find the document ID in MongoDB?

MongoDB provides a function with the name findById() which is used to retrieve the document matching the 'id' as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified 'id', it returns null.

Is MongoDB ObjectID unique across collections?

According to MongoDB, ObjectID can be considered globally unique. The first nine bytes in a MongoDB _ID guarantee its uniqueness across machines and processes, in relation to a single second; the last three bytes provide uniqueness within a single second in a single process.

What is Meteor in MongoDB?

Meteor stores data in collections. To get started, declare a collection with new Mongo.


1 Answers

Use Meteor.Collection.ObjectID:

var oid = new Meteor.Collection.ObjectID("a86ce44f9a46b99bca1be7a9");
var doc = SomeCollection.findOne(oid);

See the options for how unique IDs in collections are generated. However, it's general practice in Meteor to use the string approach because clients can then generate unique IDs reliably.

like image 179
Andrew Mao Avatar answered Sep 23 '22 09:09

Andrew Mao