FeathersJS Date is saved to database as string - mongodb

I'm using FeathersJS.
I'm trying to patch a document changing a field with a Date object into a MongoDB database, but I get this field saved as a string and not as a Date object. I'm also using the setNow() hook, and I can see that the field specified in the setNow() hook is saved as a Date, but my field is saved as a string.
Does anybody know why this is happening?

The restriction is that MongoDB itself (unlike Mongoose) does not have a schema so all user submitted data in the body or the query will have to be converted into the type that you need to save in or query from the database in a hook. This is documented here. In your case it would be
app.service('users').hooks({
before: {
create(context) {
context.data.myDate = new Date(context.data.myDate);
return context;
}
}
});

Related

When creating data in MongoDB, there was an automatically generated value, how can I control it?

First, I will show you two pictures of data recorded in MongoDB Compass.
[User Collection]
[Plan Collection]
As you can see I get only 3 values ​​from the user in the User collection: name, phone and address. It is understood that _id is automatically generated through ObjectID when such information is received, but I do not know why _class is created. When _class contains user information that I created myself, class information for use is entered as a string value. ex) "com.example.User".
Plan collection also receives 11 data from index to createdAt from the user, and _id is automatically generated through ObjectID. But here we get __v instead of _class, and this value will always exist as 0.
For reference, I did not implement the way the Plan Collection is saved, but I implemented the way the User Collection is saved through Spring boot.My Repository Interface looks like this:
#Repository
public interface UserRepository extends MongoRepository<User, String> {
}
Is the creation of _class a result of using MongoRepository?
Are __v or _class necessary values?
How can I get rid of it if I don't need it?
Can developers change the name themselves?

Flow Router doesn't work with ObjectID. Any fix?

I'm trying to build routes in my Meteor app. Routing works perfectly fine but getting information from db with route path just doesn't work. I create my page specific routes with this:
FlowRouter.route('/level/:id'...
This route takes me to related template without a problem. Then I want to get some data from database that belong to that page. In my template helpers I get my page's id with this:
var id = FlowRouter.getParam('id');
This gets the ObjectID() but in string format. So I try to find that ObjectID() document in the collection with this:
Levels.findOne({_id: id});
But of course documents doesn't have ObjectIDs in string format (otherwise we wouldn't call it "object"id). Hence, it brings an undefined error. I don't want to deal with creating my own _ids so is there anything I can do about this?
PS: Mongo used to create _ids with plain text. Someting like I would get with _id._str now but all of a sudden, it generates ObjectID(). I don't know why, any ideas?
MongoDB used ObjectIds as _ids by default and Meteor explicitly sets GUID strings by default.
Perhaps you inserted using a meteor shell session in the past and now used a mongo shell/GUI or a meteor mongo prompt to do so, which resulted in ObjectIds being created.
If this happens in a development environment, you could generate the data again.
Otherwise, you could try to generate new _ids for your data using Meteor.uuid().
If you want to use ObjectId as the default for a certain collection, you can specify the idGeneration option to its constructor as 'MONGO'.
If you have the string content of an ObjectId and want to convert it, you can issue
let _id = new Mongo.ObjectID(my23HexCharString);

Meteor JS : How to get latest set of data based on the date?

I have a requirement where my db has say some set of records with same timestamp (latest) and i want to get all of them at once, i don't want to get any other data which doesn't belong to that criteria, problem is i will not know the timestamp because it stored in db from outside world.
How do i get only the latest set of data in meteor ? i cant do findOne, as it will bring only 1 latest record, which is wrong in my case.
Meteor.publish("collection1", function() {
return Collection1.find({}, {sort:{dateTime: -1}});
});
I tried to do above code but it gets all the record and i think it just sort by desc.
Use the findOne() method to get the latest dateTime value that you can then use as the find() query:
// on the server
Meteor.publish("collection1", function() {
var latest = Collection1.findOne({}, {"sort":{"dateTime": -1}}).dateTime;
return Collection1.find({"dateTime": latest});
});
// on the client
Meteor.subscribe("collection1");
Collection1.find().fetch();
The above approach makes your Meteor app scalable client-side as the client only subscribes to the data that you only need. This is made possible because the return statement inside the Meteor.publish function can only return documents that have the latest dateTime value. This way, you'll avoid overloading the browser's memory no matter how big your server-side database is.

Convert string to Mongo ObjectID in Javascript (Meteor)

I have a Meteor application whereby I initially use the _id field from each record in my collection when naming list items in my template.
When get the _id field, I convert it to a string to use in the template.
Now I want to update these records in Mongo and am passing the _id back to a Meteor.method, but these are still in string format and Mongo is expecting an ObjectID(). Is there a simple way to convert this string to the ObjectID()? If not, what alternatives do I have?
Ok, found it! On the /server, within your Meteor method function do this to convert it:
var mid = new Mongo.ObjectID(str_id_sent_to_server);

Need to remove ObjectID() from _id using 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 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