Need to remove ObjectID () from _id with Meteor

I am retrieving records from Mongo using Meteor. I use the {{_id}} placeholder in my meteor template to use the _id field of the entry, but it adds this to my template ....

ObjectID("54f27a1adfe0c11c824e04e9") 

... and I would just like to have ...

 54f27a1adfe0c11c824e04e9 

How to do it?

+6
source share
4 answers

Just add a global helper:

 Template.registerHelper('formatId', function(data) { return (data && data._str) || data; }); 

You can also do this using ES6 syntax:

 Template.registerHelper('formatId', (id) => (id && id._str) || id); 

And use it in any template as follows:

 {{formatId _id}} 

This will work for both Mango-style ObjectIds and random meteorite-style strings.

+11
source

Since your documents use the MongoDB identifier format rather than the standard Meteor ID format (just a randomly generated string), you will need to use the MongoDB ObjectId.toString() function described. But, unfortunately, this simply causes your ObjectID to print as a string of type ObjectID("54f27a1adfe0c11c824e04e9") .

I would recommend creating a document identifier template helper that will clear your document identifiers before including them in the template. Since this problem is most likely related to all of your documents in all your collections, I would also suggest creating a global template helper. This can be done like this:

 Template.registerHelper('cleanDocumentID', function(objectID) { var objectIdString = objectID.toString(); var cleanedString = objectIDString.slice(objectIDString.indexOf('"') + 1, -2); return cleanedString; }); 

This template helper only cuts the actual string of the object identifier from the string provided by the ObjectId.toString() function. You can use this template helper in your templates like this:

 {{cleanDocumentID _id}} 

I know this is a lot more messy than just using the document identifier in the template, for example {{_id}} , but this is necessary because your documents have a document identifier of type ObjectID of type MongoDB, and not a simple random generated string used Meteor by default.

If you want to learn more about how to configure MongoDB collections to use randomly generated strings for document identifiers and avoid this mess, check out this .

+1
source

mongo is capable of storing many types, including uuids and custom. a field is usually a self-describing object consisting of a type and an identifier.

your entry uses the default mongo format, confirmed by the "ObjectId" prefix.

try ObjectId("507f191e810c19729de860ea").str

0
source

In Blaze templates, just add this {{_id.valueOf}} and you will have the string value of the actual object identifier.

0
source

Source: https://habr.com/ru/post/984367/


All Articles