简体   繁体   English

Mongo:通过ObjectId查找未在流星中定义?

[英]Mongo: find by ObjectId is not defined in meteor?

I am using existing Mongodb in meteor project. 我在流星项目中使用现有的Mongodb。 The existing mongo id represented by ObjectId() . 现有的mongo id由ObjectId()表示。 When I try to find by _id , Meteor says ObjectId is not defined 当我试图通过_id找到时,Meteor表示ObjectId is not defined

JS : 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代码在服务器中运行。

You have to use new Mongo.ObjectID("5539d9dcf046be5b2302aefc") . 您必须使用new Mongo.ObjectID("5539d9dcf046be5b2302aefc") See the meteor docs for some caveats. 有关一些警告,请参阅流星文档

If you want to save having to type new and Mongo. 如果你想节省必须键入newMongo. each time, you can define a function: 每次,你都可以定义一个函数:

function ObjectId(hexString) { return new Mongo.ObjectID(hexString); };

and then the code you wrote will work. 然后你编写的代码将起作用。

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")

If you are using mongojs: 如果您使用的是mongojs:

db.mycollection.findOne({
    _id: mongojs.ObjectId('your object id')
}, function(err, doc) {
    //do your stuff here.
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM