I am using existing Mongodb in meteor project. The existing mongo id represented by ObjectId()
. When I try to find by _id
, Meteor says ObjectId is not defined
我在流星项目中使用现有的Mongodb。现有的mongo id由ObjectId()表示。当我试图通过_id找到时,Meteor表示没有定义ObjectId
JS:
Names = new Mongo.Collection('name_list', {idGeneration: 'MONGO'});
Names.find({"_id" : ObjectId("5539d9dcf046be5b2302aefc")}) //ReferenceError: ObjectId is not defined
The above JavaScript code is run in server.
上面的JavaScript代码在服务器中运行。
3 个解决方案
#1
You have to use new Mongo.ObjectID("5539d9dcf046be5b2302aefc")
. See the meteor docs for some caveats.
您必须使用新的Mongo.ObjectID(“5539d9dcf046be5b2302aefc”)。有关一些警告,请参阅流星文档。
If you want to save having to type new
and Mongo.
each time, you can define a function:
如果你想节省必须键入新和Mongo。每次,你都可以定义一个函数:
function ObjectId(hexString) { return new Mongo.ObjectID(hexString); };
and then the code you wrote will work.
然后你编写的代码将起作用。
#2
You just need to require the ObjectId function from your mongo.
您只需要从您的mongo中获取ObjectId函数。
ObjectId = require('mongodb').ObjectID;
Then you can use it like that:
然后你就可以这样使用它:
ObjectId("5539d9dcf046be5b2302aefc")
#3
If you are using mongojs:
如果您使用的是mongojs:
db.mycollection.findOne({
_id: mongojs.ObjectId('your object id')
}, function(err, doc) {
//do your stuff here.
})
#1
You have to use new Mongo.ObjectID("5539d9dcf046be5b2302aefc")
. See the meteor docs for some caveats.
您必须使用新的Mongo.ObjectID(“5539d9dcf046be5b2302aefc”)。有关一些警告,请参阅流星文档。
If you want to save having to type new
and Mongo.
each time, you can define a function:
如果你想节省必须键入新和Mongo。每次,你都可以定义一个函数:
function ObjectId(hexString) { return new Mongo.ObjectID(hexString); };
and then the code you wrote will work.
然后你编写的代码将起作用。
#2
You just need to require the ObjectId function from your mongo.
您只需要从您的mongo中获取ObjectId函数。
ObjectId = require('mongodb').ObjectID;
Then you can use it like that:
然后你就可以这样使用它:
ObjectId("5539d9dcf046be5b2302aefc")
#3
If you are using mongojs:
如果您使用的是mongojs:
db.mycollection.findOne({
_id: mongojs.ObjectId('your object id')
}, function(err, doc) {
//do your stuff here.
})