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.
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>,
...
}
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.
Related
I want to make sure I only have one instance a documents that is an agreement between to entities... I may have modeled this wrong, so Im looking for suggestions if there is a better way to do this.
but in essence, the document looks like this.
{
_id:objectid,
entity_Ids: [objectid]
}
I was curious what's the best way to make sure the array is unique so id I do
db.agreements.insert(entity_Ids:[1,2]) and there is already a 1,2 I'll get a conflict.
I could have done it like this :
{
_id:objectid,
entity1: objectid,
entity2: objectid
}
but then I'd always have to do a check of where entit1=1 or entity2=1 or entity1=2 or entity2=2
you can create unique index on any key in the document
so in your case try
db.myCollection.createIndex({entity_Ids: 1},{unique: true});
I have a collection list such:
{username: 'somename',
friendId: '57d725d6b8b144044602bf74' <-- This a reference objectId to another doc
}
When I query docs in my collection with criteria {friendId : '57d725d6b8b144044602bf74'} I get no results back .
Any other field query works fine.
I tried to convert the value to ObjectId('57d725d6b8b144044602bf74') even though the value is just a string, still no go.
Why am I failing to search for by that type of string ?
you are trying to achieve 'self-join' in mongoDB and you seems to rely on the _id field generated by mongodb.
i would suggest you to supply custom _ID fields to the document.
eg:
{_id:"alex", name:"alex", friendID:""}
{_id"john", name"john", friendID:"alex"}
and then you can execute your queries with ease on friendID field. Give it a shot and see if this make sense for your requirement.
I am retrieving records from Mongo using Meteor. I use the {{_id}} placeholder in my meteor template to use the _id field of the record, but it adds this into my template....
ObjectID("54f27a1adfe0c11c824e04e9")
... and I would like just to have...
54f27a1adfe0c11c824e04e9
How do I do this?
Just add a global helper:
Template.registerHelper('formatId', function(data) {
return (data && data._str) || data;
});
You can also do it like this with ES6 syntax :
Template.registerHelper('formatId', (id) => (id && id._str) || id);
And use it in any template like this:
{{formatId _id}}
This will work for both mongo-style ObjectIds and meteor-style random strings.
Since your documents are using the MongoDB ID format rather than the default Meteor ID format (simply a randomly generated string), you will need to use the MongoDB ObjectId.toString() function described here. But unfortunately, this simply results in your ObjectID being printed out as a string like ObjectID("54f27a1adfe0c11c824e04e9").
I would recommend creating a document ID template helper that cleans your document IDs before including them in the template. Since this issue is most likely related to all of your documents in all of your collections, I would further suggest creating a global template helper. This can be done like so:
Template.registerHelper('cleanDocumentID', function(objectID) {
var objectIdString = objectID.toString();
var cleanedString = objectIDString.slice(objectIDString.indexOf('"') + 1, -2);
return cleanedString;
});
This template helper slices out just the actual object ID string from the string provided by the ObjectId.toString() function. You can use this template helper in your templates like so:
{{cleanDocumentID _id}}
I know that this is a lot messier than simply using the document ID in the template like {{_id}}, but it is necessary due to the fact that your documents have the MongoDB ObjectID-type document ID rather than the simple randomly generated string as used by Meteor by default.
If you would like to learn more about how to set your MongoDB collections to use randomly generated strings for document IDs and avoid this mess, check out this.
In Blaze templates, just add this {{_id.valueOf}}, and you will have a string value of the actual Object Id.
mongo is capable of storing many types including uuids and custom ones. the field is usually a self-describing object, comprised of the type and the id.
your record is using the default mongo format evidenced by the "ObjectId" prefix.
try ObjectId("507f191e810c19729de860ea").str
From the looks of the syntax for handling mongodb related things in meteor it seems that you always need to know the collection's name to update, insert, remove or anything to the document.
What I am wondering is if it's possible to get the collection's name from the _id field of a document in meteor.
Meaning if you have a document with the _id equal to TNTco3bHzoSFMXKJT. Now knowing the _id of the document you want to find which collection the document is located in. Is this possible through meteor's implementation of mongodb or vanilla mongodb?
As taken from the official docs:
idGeneration String
The method of generating the _id fields of new documents in this collection. Possible values:
'STRING': random strings
'MONGO': random Meteor.Collection.ObjectID values
The default id generation technique is 'STRING'.
Your best option would be to insert records within a pseudo transaction where the second step is to take the id and collection name to feed it into a reference collection. Then, you can do your lookups from that.
It would be pretty costly, though to construct your find's but might be a pattern worthwhile exploring if you are building an app where your users will be creating arbitrary data patterns.
You could accomplish this by doing a findOne on all of the collections:
var collectionById = function(id) {
return _.find(_.keys(this), function(name) {
if (this[name] instanceof Meteor.Collection) {
if (this[name].findOne(id)) {
return true;
}
}
});
};
I tested this on both the client and the server and it seemed to work when run in the global context.
I am new user for MongoDB Database. In MongoDb whatever insert into some collection defaultly one field is added that is _id field.
For Example:
db.users.insert({"User_id":"1","User_Name":"xxx","Address":"yyyy"})
db.users.find()
It shows
{ "_id" : ObjectId("528475fc326b403f580d2eba"), "User_id" : "1", "User_Name" : "xxx",Address" : "yyyy" }
I don't need _id field and i want to replace that _id field to User_id with auto increment values.
Is it possible. Please help me. Thanks in advance.
_id field is really special in mongodb. This is your primary key there and there is no way you can have a document without it. Even if you are trying to insert the document without it, mongo will create it for you (as in your example). Moreover, you can not even modify _id field for you collection.
But you can create a document with your own _id. So if you want you can do db.users.insert({"_id":"1","User_Name":"xxx","Address":"yyyy"}) \\why exactly 1 is a string?
and remember that _id means user_id and also keep in mind that this _id should be unique
Keep in mind that mongodb is not like sql. It does not have autoincrement keys (by this I mean that it is not that creators did not know how to do it, but just that you can leave pretty much without it), but you can achieve create something that would resemble the same behaviour.
As for as I can understand your problem is that you want to use your mongoDB internal _id as your custom attribute. For example suppose the db contain the user Identity and having attributes like "_id , name , address ..." and you want to use this _id's value in your application as userId for external reference.
So as #SalvadorDali said _id field is really important in the mongoDB and you can not have a document without it. All you can do is let the db store the value by it's default _id but you can access outside using your own User_id by applying these two changes in your json file.
"properties": {
"userId":{
"type": "string",
"id":"true",
"index":"true",
"description": "unique id of identity"
}
}
now you store any unique value, it is stored in the db using default _id and outside you can have that value in userId field.
Correct me if i got your question wrong.