如何使用Mongoose生成ObjectID?

我想用Mongoose生成一个MongoDB__abc0。有没有一种方法可以从Mongoose访问ObjectId构造函数?

  • 这个问题是关于从零开始生成一个新ObjectId。生成的ID是一个全新的通用唯一ID.

  • 另一个问题询问如何从现有的字符串表示形式创建ObjectId。在本例中,您已经有了一个ID的字符串表示—它可能是也可能不是全局惟一的—并且您正在将其解析为ObjectId

190487 次浏览

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.


Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new:

var id = new mongoose.Types.ObjectId();

You can read more about the Types object at Mongoose#Types documentation.

You can create a new MongoDB ObjectId like this using mongoose:

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

I needed to generate mongodb ids on client side.

After digging into the mongodb source code i found they generate ObjectIDs using npm bson lib.

If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson library :

const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2

Note: There is also an npm project named bson-objectid being even lighter

With ES6 syntax

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