Pavan Kumar
Pavan Kumar

Reputation: 1881

Meteor collection weird behavior.

I have collection "config" as follows.

Config= new Mongo.Collection("config");

Config collection contains configuration data which will be loaded to DB from backend and never would be edited by Meteor.

Following is sample data in config:

{
    _id: 0,
    name: "S"
}

{
    _id: 1,
    name: "M"
}

{
    _id: 2,
    name: "L"
}

Note: _id is Integer.

Following code is run on server and results are inconstant.

Config.findOne(0); //result is undefined
Config.findOne({_id: 0}); //result is undefined

Config.findOne(1); //result is { _id: 1,Name:"M"}
Config.findOne({_id: 1}); //result is { _id: 1,Name:"M"}

Following code is run in browser and results are again inconstant.

Config.findOne(0); //result is { _id: 0,Name:"S"}
Config.findOne({_id: 0}); //result is undefined

Config.findOne(1); //result is { _id: 1,Name:"M"}
Config.findOne({_id: 1}); //result is { _id: 1,Name:"M"}

Why findOne is behaving differently when _id is 0

Note: Meteor version 1.1.0.2 on Windows 8.1

Upvotes: 0

Views: 40

Answers (1)

Tarang
Tarang

Reputation: 75945

It is not mentioned in the docs but Meteor ignores documents where the id is a falsey value, such as 0.

This is because it is problematic since the _id is used as a reference to identify documents when transmitting data through DDP.

There is no workaround for this. Try beginning your _id field at 1 instead.

It is also advisable to use the randomly generated _id's. The reason for this is your clients may have insert operations that can have latency between when they are sent and inserted.

The result of this is the _ids would not necessarily match the order they were created in. The exception to this is when they are created entirely and only on the server.

Meteor also prevent's the insertion of documents with falsey _ids (see https://github.com/meteor/meteor/blob/devel/packages/mongo/collection.js#L322-L325). But this wont help if you insert the documents from mongo.

This is the reason the _id field is currently random and bears no timestamp-like property.

Upvotes: 1

Related Questions