node.js 如何使用猫鼬生成 ObjectId?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17899750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I generate an ObjectId with mongoose?
提问by Dmitry Minkovsky
I'd like to generate a MongoDB ObjectIdwith Mongoose. Is there a way to access the ObjectIdconstructor from Mongoose?
我想ObjectId用猫鼬生成一个 MongoDB 。有没有办法ObjectId从 Mongoose访问构造函数?
This question is about generating a new
ObjectIdfrom scratch. The generated ID is a brand new universally unique ID.Another question asks about creating an
ObjectIdfrom an existing string representation. In this case, you already have a string representation of an ID—it may or may not be universally unique—and you are parsing it into anObjectId.
这个问题是关于从头开始生成一个新的
ObjectId。生成的ID是一个全新的通用唯一ID。另一个问题是关于
ObjectId从现有字符串表示创建。在这种情况下,您已经有一个 ID 的字符串表示形式——它可能是也可能不是普遍唯一的——并且您正在将它解析为一个ObjectId.
回答by Dmitry Minkovsky
You can find the ObjectIdconstructor on require('mongoose').Types. Here is an example:
您可以在ObjectId上找到构造函数require('mongoose').Types。下面是一个例子:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
idis a newly generated ObjectId.
id是一个新生成的ObjectId.
You can read more about the Typesobject at Mongoose#Types documentation.
您可以Types在Mongoose#Types 文档中阅读有关该对象的更多信息。
回答by steampowered
You can create a new MongoDB ObjectIdlike this using mongoose:
您可以ObjectId使用 mongoose 像这样创建一个新的 MongoDB :
var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();
回答by Poyoman
I needed to generate mongodb ids on client side.
我需要在客户端生成 mongodb id。
After digging into the mongodb source code i found they generate ObjectIDs using npm bsonlib.
在深入研究 mongodb 源代码后,我发现它们使用 npm bsonlib生成 ObjectID 。
If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bsonlibrary :
如果您只需要生成一个 ObjectID 而无需安装整个 mongodb / mongoose 包,您可以导入更轻的bson库:
const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2
Note: There is also an npm project named bson-objectidbeing even lighter
注意:还有一个名为bson-objectid更轻量级的 npm 项目
回答by MattCochrane
With ES6 syntax
使用 ES6 语法
import mongoose from "mongoose";
// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

