乐闻世界logo
搜索文章和话题

How can i generate an objectid with mongoose

5 个月前提问
3 个月前修改
浏览次数110

6个答案

1
2
3
4
5
6

在 Mongoose 中,ObjectId 是 MongoDB 的一种数据类型,用于唯一标识文档。Mongoose 使用 MongoDB 下层的 bson 库来生成 ObjectId

当你在 Mongoose 模型中定义了一个字段类型为 ObjectId,比如在用户模型的定义中:

js
const mongoose = require('mongoose'); const { Schema } = mongoose; const userSchema = new Schema({ name: String, // 定义 ObjectId 类型字段 _id: Schema.Types.ObjectId }); const User = mongoose.model('User', userSchema);

在你创建一个新文档并保存到数据库中时,Mongoose 会自动为这个 _id 字段生成一个新的 ObjectId。例如:

js
const newUser = new User({ name: 'John Doe' }); newUser.save((err, savedUser) => { if (err) throw err; // savedUser._id 将会是一个自动生成的 ObjectId console.log(savedUser._id); });

如果你没有显式地在你的模型定义中声明 _id 字段,Mongoose 会默认为你的每个文档添加一个 _id 字段,并自动生成一个 ObjectId

ObjectId 是一个 12 字节的值,通常由以下几部分构成:

  1. 4字节的时间戳,表示 ObjectId 的创建时间。
  2. 5字节的随机值,为了确保在同一时间生成的 ObjectId 是唯一的。
  3. 3字节的增量计数器,从随机值开始。

这种结构确保即使在大量操作下,生成的 ObjectId 也是唯一且按时间顺序排列的。

在某些情况下,你可能需要手动生成一个 ObjectId。你可以使用 Mongoose 提供的 Types 对象来做到这一点:

js
const { Types } = require('mongoose'); const objectId = new Types.ObjectId();

现在 objectId 变量就包含了一个新生成的 ObjectId 实例,可以用在任何需要 ObjectId 的地方。

2024年6月29日 12:07 回复

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

shell
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:

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

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

2024年6月29日 12:07 回复

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

shell
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();
2024年6月29日 12:07 回复

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 :

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

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

2024年6月29日 12:07 回复

With ES6 syntax

shell
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');
2024年6月29日 12:07 回复

The import is mongo from mongoose, the node-mongodb-native driver. If you open the package you can verify !

shell
import { mongo } from 'mongoose' const newId = new mongo.ObjectId()
2024年6月29日 12:07 回复

你的答案