Reputation: 1277
I'm trying to put a prefix before the auto generated _id
, to identify from which collection came an id, but I still want to use the mongo unique id generator.
So I can know that this id model_5e1a51821c9d44000089e3e0
came from the Model collection.
Is there a solution for that without messing with random string ?
Edit
The _id
need to be string castable, since I use it as id
in a graphQL object. I need to differentiate ids because I use an union in my schema and resolver need to know in which table to find the data.
Upvotes: 2
Views: 3199
Reputation: 14287
The _id
can be generated within an application with the constructor ObjectId()
. If you want to add a prefix for the generated field, you can use an embedded document as a field for the _id
, like this:
_id: {
idPrefix: "Model",
_id: ObjectId("5e1bd112b7f18a490a4bafb5")
}
Other way of identifying if a document is from another collection is use a separate boolean
field:
{
_id: ObjectId("5e1bd112b7f18a490a4bafb5"),
isFromModel: <boolean true or false>,
...
}
Upvotes: 2
Reputation:
There are some options available to do this, I'm just trying to tell you the way how would I do if I need this.
Step 1: You can generate the document and it will return you ObjectId (_id) .
Step 2: Take that value and prefix it with model like this.
let _id=5e1a51821c9d44000089e3e0;let new_idValue="model_"+_id;
Step3: Now update your document by _id and push new value in place of if as
this.db.document.findByIdAndUpdate(_id,{$set:{{_id:new_idValue}})
This is what you can do. If you find some best solution than mine, let me know as well. I will highly appreciate.
Upvotes: 0