如何使用猫鼬生成 ObjectId? [英] How can I generate an ObjectId with mongoose?
问题描述
我想用 Mongoose 生成一个 MongoDB ObjectId
.有没有办法从 Mongoose 访问 ObjectId
构造函数?
I'd like to generate a MongoDB ObjectId
with Mongoose. Is there a way to access the ObjectId
constructor from Mongoose?
这个问题是关于从头开始生成一个新的
ObjectId
.生成的 ID 是一个全新的通用唯一 ID.
This question is about generating a new
ObjectId
from scratch. The generated ID is a brand new universally unique ID.
另一个问题是关于从现有字符串表示创建ObjectId
.在这种情况下,您已经有一个 ID 的字符串表示形式——它可能是也可能不是普遍唯一的——并且您正在将它解析为一个 ObjectId
.
Another question asks about creating an ObjectId
from 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 an ObjectId
.
推荐答案
您可以在 require('mongoose').Types
上找到 ObjectId
构造函数.下面是一个例子:
You can find the ObjectId
constructor on require('mongoose').Types
. Here is an example:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
id
是新生成的ObjectId
.
注意:作为 Joshua Sherman 指出,对于 Mongoose 6,您必须在调用前加上 new
:
Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new
:
var id = new mongoose.Types.ObjectId();
您可以在 Mongoose#Types 文档中阅读有关 Types
对象的更多信息.
You can read more about the Types
object at Mongoose#Types documentation.
这篇关于如何使用猫鼬生成 ObjectId?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!