MongoDB _id会自动转换为ObjectID,但有时不会. [英] MongoDB _id is convert to ObjectID automatically, but sometime it is not.

查看:561
本文介绍了MongoDB _id会自动转换为ObjectID,但有时不会.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个名为 mongoskin 的包装器来访问mongoDB. mongoskin是围绕mongoDB javascript API的简单包装.

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

但是当我写到mongoDB时,有时_id会转换为ObjectID,有时不是.当我必须比较_id时,不同的行为会引起很多问题.例如:

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:

公司集合中的以下文档创建者"不会转换为ObjectID,但是客户"中的项目会自动转换为ObjectID.

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

这是我用来为_id分配_id的nodejs代码

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

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

这是我用来为_id分配_id的nodejs代码

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) { ...}

当我console.log"req.session.user.company_id"和"resultClient._id"时,它们看起来都像是字符串类型.在MongoDB中如何最终成为ObjectID?如果有自动转换,如何使这种行为一致?

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?

谢谢!

推荐答案

我猜resultClient是查询的结果,而req.session.user.company_id是Web应用程序中的字符串?在这种情况下,您需要根据字符串创建一个ObjectId:

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

这篇关于MongoDB _id会自动转换为ObjectID,但有时不会.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆