6 mongoose node.js express backbone.js
如何将ObjectId转换为数字?在我的应用程序中,我在客户端使用最新的mongoose版本和主干.
我的问题是,ObjectId总是最终放在引号之间,这会在我的jade模板和我的客户端上产生双引号,例如""233453452534"".
编辑:
我在跟mongodb查询
this.users.find({},function(err,docs){
cb(null,docs)
})
Run Code Online (Sandbox Code Playgroud)
console.log(docs)显示
{ name: 'test',
_id: 5220bc207f0c866f18000001,
__v: 0 }
Run Code Online (Sandbox Code Playgroud)
在我的模板中
option(data-id=val._id) #{val.name}
Run Code Online (Sandbox Code Playgroud)
我将此传递给res.render
res.render('test.jade',docs)
Run Code Online (Sandbox Code Playgroud)
和我的HTML渲染:
""5220bb43b754af4118000001""
Run Code Online (Sandbox Code Playgroud)
双引号arround我的对象id.我试图在一个模式中设置一个数字,这是有效的,如果它是一个数字,没有引号括起来,所以我猜这是因为它是一个objectID.
Jes*_*ton 10
这是未经测试的,但我认为你想做这样的事情:
var idNum = parseInt(objectId.valueOf(), 16);
Run Code Online (Sandbox Code Playgroud)
MongoDB ObjectID基本上是12字节的十六进制字符串.这使得它们大于MAX_VALUEJavaScript编号(2 ^ 53),因此您可能会遇到转换错误.但是,看起来Number.MAX_VALUE我的node.js环境(0.11.6)可以处理该值.所以你可能很安全......
为什么要将对象ID转换为数字?你真的不应该在ObjectId上执行算术运算......
我假设您希望对象的唯一 id 作为整数/数字(有时只是一个易于最终用户使用的小整数)。我对票号有相同的用例。有时您希望最终用户能够直接引用记录 ID,但没有那些时髦的字符。所以人们真的想把它转换成一个简单的整数,例如:000001 而不是 5220bb43b754af4118000001。
在这里我主要是回答问题的标题以帮助我和其他人,我希望它可以回答问题。
实际上,对于上述用例或大多数用例,您不需要转换整个对象 id:
根据这个https://devopslog.wordpress.com/2012/04/22/disassemblereassemble-mongodb-objectids/
timestamp ? Generation timestamp (4 bytes)
machine ? First 3 bytes of the MD5 hash of the machine host name, or of the mac/network address, or the virtual machine id.
pid ? First 2 bytes of the process (or thread) ID generating the ObjectId.
inc ? ever incrementing integer value.
Run Code Online (Sandbox Code Playgroud)
在字符中,这转化为:
timestamp ? 0-7
machine ? 8-13
pid ? 14-17
inc ? 18-23
Run Code Online (Sandbox Code Playgroud)
意思是:
“5220bb43b754af4118000001”
被分解为:
timestamp ? 5220bb43
machine ? b754af
pid ? 4118
inc ? 000001
Run Code Online (Sandbox Code Playgroud)
您可能只需要 ID 的 inc 部分或至少需要时间戳和 inc。
timestamp ? Generation timestamp (4 bytes)
machine ? First 3 bytes of the MD5 hash of the machine host name, or of the mac/network address, or the virtual machine id.
pid ? First 2 bytes of the process (or thread) ID generating the ObjectId.
inc ? ever incrementing integer value.
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助某人。
尝试使用虚拟 id 而不是 _id
option(data-id=val.id) #{val.name}
Run Code Online (Sandbox Code Playgroud)
代替
option(data-id=val._id) #{val.name}
Run Code Online (Sandbox Code Playgroud)