I have:
dates = {}
today = new Date()
todayminus7days = new Date(today).setDate(today.getDate()-7)
dates.startDate = todayminus7days
dates.endDate = today
query =
person_gender: filter.gender if filter.gender
person_age:
0:
$gte: dates.startDate
1:
$lte: dates.endDate
However, when I run this query through a Mongoose model, the end query is:
{ person_gender: 'female',
person_age:
{ '0': { '$gte': 1317055089524 },
'1': { '$lte': Mon, 03 Oct 2011 16:38:09 GMT } } }
and this returns null results within that date range.
How can I pass Date's to Mongoose then?
Your problem here is not MongoDB or Mongoose related, but in your assumption that .setDate() returns a Date (which it doesn't).
If you change your initialization code to:
...
todayminus7days = new Date(today);
todayminus7days.setDate(-7);
...
It should work as expected.
Related
i have a problem with mongoDB, im trying to create trigger, that will take server date and compare it with property DueDate and if the DueTime is lesser or equal of the server time, it should swap property borrowed to false.
Problem is that it didnt work and im so lost i tried everything.
There is my trigger function:
exports = function(changeEvent) {
const mongo = context.services.get("MongoDB");
const now = new Date();
const booksLended = mongo.db("test").collection("bookslendeds");
var filter = {DueDate: {$lt: now.toISOString()}, Borrowed: true};
var update = {$set: {Borrowed: false}};
console.log(JSON.stringify(filter));
console.log(JSON.stringify(update));
return booksLended.updateMany(filter, update);
};
This is a console logs:
> ran on Wed Jan 18 2023 23:48:10 GMT+0100 (Central European Standard Time)
> took 524.689137ms
> logs:
{"DueDate":{"$lt":"2023-01-18T22:48:11.778Z"},"Borrowed":true}
{"$set":{"Borrowed":false}}
> result:
{
"matchedCount": {
"$numberInt": "0"
},
"modifiedCount": {
"$numberInt": "0"
}
}
> result (JavaScript):
EJSON.parse('{"matchedCount":{"$numberInt":"0"},"modifiedCount":{"$numberInt":"0"}}')
DataModel
The datatype of the DueDate field is probably UTC datetime, while .toISOString() is returning a string. MongoDB query operators are type-sensitive, so these will not match.
Instead, use the date object directly in the query, like:
var filter = {DueDate: {$lt: now}, Borrowed: true};
This Meteor server code tries to count all the records which are 4 months and newer with property size:'4', color:'white' but account all entires from any one user as one count, so no mater how many documents have been entered by the same user, the are all counted as one. but I am getting nothing in return. any ideas? thx
let date = new Date();
date.setMonth(date.getMonth() - 4);
let doc = UsageCol.aggregate([{
$match: {
createdAt: {
$gte: date,
$lte: new Date()
},
action: 'failBroadcast',
plate: plate
}
}, {
$group: {
_id: {
userId: "$userId"
},
count: {
$sum: 1
}
}
}]);
for (var i = 0; i < doc.length; i++) {
var obj = doc[i];
console.log(JSON.stringify(obj));
}
Alright I just wanted to clear some things up from this morning.
The only reason I recommended moment js was thinking we are storing the date in date type and there is no easy way to dynamically create date in UTC using java script date function
So now that we know you used Date.now() to save the dates, you don't need any moment js.
The correct syntax is
let dateToMillis = Date.now(); //The current millis from epoch.
let dateFrom = new Date(dateToMillis); // Use the current millis from epoch.
let dateFromMillis = dateFrom.setMonth(dateFrom.getMonth() - 4); // The millis 4 months ago from epoch.
Pass dateToMillis and dateFromMillis to aggregation query.
Hi everyone i'm working with meteor js and i'm trying to get all documents from a mongoDB collection created at a specific hour of the day for example today at 8am how can i do this?
i'll be thankfull for any help
When you create your documents, you must set the creation date:
MyCollection.insert({ text: "abc", createdAt: new Date() });
then, you can filter your data:
If you want the documents created in an interval:
MyCollection.find(
{createdAt: {
$gte: new Date("Sat Jul 30 2016 8:00:00"),
$lt: new Date("Sat Jul 30 2016 9:00:00"),
}},
{sort: {createdAt:1}});
Or documents created exactly at 8am:
MyCollection.find({createdAt: new Date("Sat Jul 30 2016 8:00:00")});
Hope it helps.
If you are using collection 2 package, you have to add this to your collection
createdAt: {
type: Date,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset();
}
}
After that you have to add the createdAt field to your query.
I'm new to meteorjs and mongodb. I'm having trouble finding a collection of results based on date. First I used the following meteorjs code to confirm there are records.
var application = Applications.findOne({_id:'Y3xCNck6JhABGj9e7'});
var a1 = Applications.find({owner:application.owner}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
console.log(application.createdAt); // gives Sun Dec 27 2015 09:19:17 GMT-0500 (Eastern Standard Time)
console.log(a1);
/*
This gives plenty of results. An example is
createdAt: Sun Dec 27 2015 09:16:10 GMT-0500 (Eastern Standard Time)
owner: "s4xcBwWAqSktoQuLA"
Note that the createdAt date for this particular record is before the application.createdAt, which will become relevant in the next set of queries.
*/
Now what I don't understand is why each of these statements give zero results:
var application = Applications.findOne({_id:'Y3xCNck6JhABGj9e7'});
var a2a = Applications.find({createAt:{$lt:application.createdAt}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
var a2b = Applications.find({createAt:{$lt: new Date(application.createdAt)}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
var a2c = Applications.find({createAt:{$lte:application.createdAt}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
var a2d = Applications.find({createAt:{$lte: new Date(application.createdAt)}}).map(function(app){return {owner:app.owner,createdAt:app.createdAt}});
What did I do wrong? In the a1 example, I'm sure there should be records with createdAt being less than the application.createdAt.
additional notes
When I first saved the application, I saved the date as follows:
saveApplication(formVals) {
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
formVals['appStatus'] = 1;
formVals['createdAt'] = new Date();
formVals['owner'] = Meteor.userId();
formVals['username'] = Meteor.user().username;
Applications.insert(formVals);
},
Typos:
var a2a = Applications.find({ createAt: { $lt: application.createdAt }})...
should be
var a2a = Applications.find({ createdAt: { $lt: application.createdAt }})...
I've trouble dealing with a type: Date into SimpleSchema having a defaultValue.
In mongodb (3.0.1), the date entry have the time the meteor thread have been launch. The expected behaviour is to have "date" the insertion date of the object on the server.
lib/schema.js
Schema.DateCol = new SimpleSchema({
date: {
type: Date,
defaultValue: new Date()
},
dateModified: {
type: Date,
autoValue: function () { return new Date(); }
}
});
client/home.html
{{> quickForm id="test" schema="Schema.DateCol" collection="DateCol" type="insert" }}
Into the mongo, after inserting two objects:
meteor thread launch at "Wed May 20 2015 12:28:42 GMT+0200 (CEST)"
both objects have been inserted at one minute of interval: the first at
"Wed May 20 2015 12:30:50 GMT+0200 (CEST)" and the second at "Wed May 20 2015 12:31:30 GMT+0200 (CEST)"
the date field (defaultValue) for both object is: "Wed May 20 2015 12:28:42 GMT+0200 (CEST)"
Object 1
{
"_id": "PuME9jWwJJiw9diSC",
"date": new Date(1432117722634),
"dateModified": new Date(1432117850366)
}
Object 2:
{
"_id": "qqHqkN4YapWDsFhxx",
"date": new Date(1432117722634),
"dateModified": new Date(1432117890380)
}
You'll fin enclose a repository Github with the error, using MongoDB 3.0.1 (I haven't this error on MongoDB 2.4):
https://github.com/JVercout/meteor-defaultValue-date-errored
Any ideas?
The problem is that the new Date() expression is evaluated once when the code creating the schema is run. That value is then used as the defaultValue. There is no difference between:
var x = new SimpleSchema({
date: {defaultValue: new Date(), ...}
});
and
var defaultDate = new Date();
var x = new SimpleSchema({
date: {defaultValue: defaultDate, ...}
});
It looks like you'll need an autoValue, since it doesn't look like you can use a function for defaultValue. The Collection2 documentation actually has an example of using autoValue for a "created at" field. It depends on fields added by Collection2 but I saw in your git repo that you're using that.
// Force value to be current date (on server) upon insert
// and prevent updates thereafter.
createdAt: {
type: Date,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset();
}
}
}