我真的很喜欢 mongodb 生成的 _ids 格式。主要是因为我可以从客户端提取日期等数据。我计划使用另一个数据库,但仍然希望我的文档使用这种类型的 _id 。如何在不使用 mongodb 的情况下创建这些 id?
谢谢!
在客户端使用官方MongoDB BSON库
我有一个可以生成
ObjectId
的浏览器客户端。我想确保在客户端中使用与服务器中使用的相同的 ObjectId
算法。 MongoDB 有 js-bson 可以用来实现这一点。
如果您在 Node 中使用 javascript。
npm install --save bson
使用 require 语句
var ObjectId = require('bson').ObjectId;
var id = new ObjectId();
console.log(id.toString());
使用ES6导入语句
import { ObjectId } from 'bson';
const id = new ObjectId();
console.log(id.toString());
该库还允许您使用良好的旧脚本标签进行导入,但我还没有尝试过。
JavaScript 中的一个非常简单的伪 ObjectId 生成器:
const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>
s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h))
对象 ID 通常由客户端生成,因此任何 MongoDB 驱动程序都会有代码来生成它们。
如果您正在寻找 JavaScript,这里有来自 MongoDB Node.js 驱动程序的一些代码:
https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js
另一个更简单的解决方案:
以更易读的语法扩展 Rubin Stolk 和 ChrisV 的答案 (KISS)。
function objectId () {
return hex(Date.now() / 1000) +
' '.repeat(16).replace(/./g, () => hex(Math.random() * 16))
}
function hex (value) {
return Math.floor(value).toString(16)
}
export default objectId
这是一个生成新objectId的简单函数
newObjectId() {
const timestamp = Math.floor(new Date().getTime() / 1000).toString(16);
const objectId = timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, () => {
return Math.floor(Math.random() * 16).toString(16);
}).toLowerCase();
return objectId;
}
ruben-stolk 的回答很好,但故意不透明?比较容易区分的是:
const ObjectId = (rnd = r16 => Math.floor(r16).toString(16)) =>
rnd(Date.now()/1000) + ' '.repeat(16).replace(/./g, () => rnd(Math.random()*16));
(实际上字符数略少)。不过还是值得称赞!
这是链接!去图书馆这样做。
https://www.npmjs.com/package/mongo-object-reader 您可以读写十六进制字符串。
const { createObjectID, readObjectID,isValidObjectID } = require('mongo-object-reader'); //Creates a new immutable `ObjectID` instance based on the current system time. const ObjectID = createObjectID() //a valid 24 character `ObjectID` hex string. //returns boolean // input - a valid 24 character `ObjectID` hex string. const isValid = isValidObjectID(ObjectID) //returns an object with data // input - a valid 24 character `ObjectID` hex string. const objectData = readObjectID(ObjectID) console.log(ObjectID) //ObjectID console.log(isValid) // true console.log(objectData) /* { ObjectID: '5e92d4be2ced3f58d92187f5', timeStamp: { hex: '5e92d4be', value: 1586681022, createDate: 1970-01-19T08:44:41.022Z }, random: { hex: '2ced3f58d9', value: 192958912729 }, incrementValue: { hex: '2187f5', value: 2197493 } } */
在v5.3.0中它不是
ObjectID
而是小资本的ObjectId
。 import { ObjectId } from 'bson'