Flow Router doesn't work with ObjectID. Any fix?

人走茶凉 提交于 2019-12-31 02:25:13

问题


I'm trying to build routes in my Meteor app. Routing works perfectly fine but getting information from db with route path just doesn't work. I create my page specific routes with this:

FlowRouter.route('/level/:id'...

This route takes me to related template without a problem. Then I want to get some data from database that belong to that page. In my template helpers I get my page's id with this:

var id = FlowRouter.getParam('id');

This gets the ObjectID() but in string format. So I try to find that ObjectID() document in the collection with this:

Levels.findOne({_id: id});

But of course documents doesn't have ObjectIDs in string format (otherwise we wouldn't call it "object"id). Hence, it brings an undefined error. I don't want to deal with creating my own _ids so is there anything I can do about this?

PS: Mongo used to create _ids with plain text. Someting like I would get with _id._str now but all of a sudden, it generates ObjectID(). I don't know why, any ideas?


回答1:


MongoDB used ObjectIds as _ids by default and Meteor explicitly sets GUID strings by default.

Perhaps you inserted using a meteor shell session in the past and now used a mongo shell/GUI or a meteor mongo prompt to do so, which resulted in ObjectIds being created.

If this happens in a development environment, you could generate the data again.

Otherwise, you could try to generate new _ids for your data using Meteor.uuid().

If you want to use ObjectId as the default for a certain collection, you can specify the idGeneration option to its constructor as 'MONGO'.

If you have the string content of an ObjectId and want to convert it, you can issue

let _id = new Mongo.ObjectID(my23HexCharString);


来源:https://stackoverflow.com/questions/35712188/flow-router-doesnt-work-with-objectid-any-fix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!