Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use new Meteor.Collection.ObjectID() in my mongo queries with meteor?

Tags:

mongodb

meteor

I have a Collection that has documents with an array of nested objects. Here is fixture code to populate the database:

if (Parents.find().count() == 0) {
    var parentId = Parents.insert({
        name: "Parent One"
    });
    Children.insert({
        parent: parentId,
        fields: [
            {
                _id: new Meteor.Collection.ObjectID(),
                position: 3,
                name: "three"
            },
            {
                _id: new Meteor.Collection.ObjectID(),
                position: 1,
                name: "one"
            },
            {
                _id: new Meteor.Collection.ObjectID(),
                position: 2,
                name: "two"
            },

        ]
    });
}

You might be asking yourself, why do I even need an ObjectID when I can just update based off of the names. This is a simplified example to a much more complex schema that I'm currently working on and the the nested object are going to be created dynamically, the ObjectID's are definitely going to be necessary to make this work.

Basically, I need a way to save those nested objects with a unique ID and be able to update the fields by their _id.

Here is my Method, and the call I'm making from the browser console:

Meteor.methods({
  upChild: function( options ) {
        console.log(new Meteor.Collection.ObjectID());
        Children.update({_id: options._id, "fields._id": options.fieldId }, {$set: {"fields.$.position": options.position}}, function(error){
            if(error) {
                console.log(error);
            } else {
                console.log("success");
            }
        });
    }
});

My call from the console:

Meteor.call('upChild', {
  _id: "5NuiSNQdNcZwau92M",
  fieldId: "9b93aa1ef3868d762b84d2f2",
  position: 1
});

And here is a screenshot of the html where I'm rendering all of the data for the Parents and Children collections: enter image description here

like image 914
Scott Avatar asked Oct 07 '13 23:10

Scott


2 Answers

Just an observation, as I was looking how generate unique IDs client side for a similar reason. I found calling new Meteor.Collection.ObjectID() was returning a object in the form 'ObjectID("abc...")'. By assigning Meteor.Collection.ObjectID()._str to _id, I got string as 'abc...' instead, which is what I wanted.

I hope this helps, and I'd be curious to know if anyone has a better way of handling this?

Jason

like image 168
Raz Avatar answered Nov 15 '22 09:11

Raz


Avoid using the _str because it can change in the future. Use this:

new Meteor.Collection.ObjectID().toHexString() or

new Meteor.Collection.ObjectID().valueOf()


You can also use the official random package:

Random.id()

like image 39
Bruno Lemos Avatar answered Nov 15 '22 08:11

Bruno Lemos