MongoDB _id is convert to ObjectID automatically, but sometime it is not.

偶尔善良 提交于 2019-12-25 03:44:33

问题


I am using a wrapper called mongoskin to access mongoDB. mongoskin is a simple wrapper around mongoDB javascript api.

But when I write to mongoDB, sometimes _id is converted to ObjectID, sometime is it not. The different behavior causes many problem when I have to compare _id. For example:

The following documents in company collection, "creator" is not converted to ObjectID, but item in "clients" is converted to ObjectID automatically.

> db.company.find()
{ "_id" : ObjectId("53d4b452f5b25900005cb998"), "name" : "Default Company Co.", "clients" : [ ObjectId("53d4b452f5b25900005cb999"), ObjectId("53d4b452f5b25900005cb99a") ] }
{ "_id" : ObjectId("53d4b452f5b25900005cb999"), "name" : "client company for 777 - updated", "creator" : "53d4b452f5b25900005cb998", "ssn" : "12-123-1234" }

This is the nodejs code I used to assign _id for "creator"

clientCompany.creator = req.session.user.company_id;

This is the nodejs code I used to assign _id for "clients"

var updateObj = {$addToSet: {clients:resultClient._id} };
// update creator company.clients
creatorCompany.update(updateObj, function(err, result) { ...}

When I console.log "req.session.user.company_id" and "resultClient._id", they both looks like a string type. How come one end up as ObjectID in MongoDB? If there is an auto conversion, how do I make this behavior consistent?

Thanks!


回答1:


I'm guessing resultClient is the result of a query and req.session.user.company_id a string from your web application? In that case you need to create an ObjectId from the string:

clientCompany.creator = mongoskin.ObjectID(req.session.user.company_id);



来源:https://stackoverflow.com/questions/24979325/mongodb-id-is-convert-to-objectid-automatically-but-sometime-it-is-not

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