【发布时间】:2020-10-05 23:38:59
【问题描述】:
我有一个旧代码库,其中 parse-server 与 MongoDB 一起使用。它生成 _id 作为字符串而不是 ObjectId。我想将解析服务器替换为猫鼬。是否可以使用 mongoose 生成字符串 ID?目前我不想更改现有的 ID。你能提出什么建议?谢谢
【问题讨论】:
标签: node.js mongodb parse-server
我有一个旧代码库,其中 parse-server 与 MongoDB 一起使用。它生成 _id 作为字符串而不是 ObjectId。我想将解析服务器替换为猫鼬。是否可以使用 mongoose 生成字符串 ID?目前我不想更改现有的 ID。你能提出什么建议?谢谢
【问题讨论】:
标签: node.js mongodb parse-server
编程世界中人类已知的最古老的函数之一.toString() 可以为您完成这项工作,使用mongoose > 5.4.0 您可以使用.toString() 将任何ObjectID 转换为string。
你可以阅读它here
【讨论】:
parse-server 会生成它自己的 ID,我以为您收到了 ObjectId,并且您想将其转换为 string
从 Parse-server 代码中提取 (https://github.com/parse-community/parse-server/blob/2b26cc043e6a06f9c61ea17227a3f88e69310d14/src/cryptoUtils.js#L16)
//
// Note: to simplify implementation, the result has slight modulo bias,
// because chars length of 62 doesn't divide the number of all bytes
// (256) evenly. Such bias is acceptable for most cases when the output
// length is long enough and doesn't need to be uniform.
export function randomString(size: number): string {
if (size === 0) {
throw new Error('Zero-length randomString is useless.');
}
const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789';
let objectId = '';
const bytes = randomBytes(size);
for (let i = 0; i < bytes.length; ++i) {
objectId += chars[bytes.readUInt8(i) % chars.length];
}
return objectId;
}
// Returns a new random alphanumeric string suitable for object ID.
export function newObjectId(size: number = 10): string {
return randomString(size);
} ```
【讨论】: