I have an old codebase where parse-server is used with MongoDB. And it generate _id as a string instead of ObjectId. I want to replace parse-server to mongoose. Is it possible to generate string ids with mongoose? Currently I don't want to change existing ids. What you can suggest? Thanks
Asked
Active
Viewed 675 times
2 Answers
0
One of the oldest function known to mankind in programming world .toString()
can do the job for you, with mongoose > 5.4.0
you can convert any ObjectID
to string
using .toString()
.
You can read about it here

Shivam
- 3,514
- 2
- 13
- 27
-
1The same question https://stackoverflow.com/questions/43874830/using-mongo-bson-objectid-with-parse-server – Oleksandr Matviichuk Nov 21 '19 at 15:55
-
Ohh I had no idea that `parse-server` generates it's own ID, I thought you are getting `ObjectId` and you want to convert it to `string` – Shivam Nov 21 '19 at 15:58
-
Can I generate string _id, when I save document? – Oleksandr Matviichuk Nov 21 '19 at 16:04
-
If using MongoDB directly, yes. Through Parse Server it is not currently possible. – Davi Macêdo Dec 04 '19 at 02:19
0
Extracted from Parse-server code (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);
} ```
-
please, expand your answer to explain exactly how this code snippet could help with the issue at hand. – lucasreta Oct 05 '20 at 21:50