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};
Related
I have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :
xDate : {
type: Date.now,
required: true
}
I pass the current Date as :
var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);
However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:
X.
find({
xDate: curDate
})
.exec(function(err, doc) {
var response = {
status : 200,
message : doc
};
if (err) {
console.log('Error');
response.status = 500;
response.message = err;
} else if (!doc) {
console.log("Documents against the date not found in database" ,curDate);
response.status = 404;
response.message = {
"message" : "Documents not found for " + curDate
};
}
res
.status(response.status)
.json(response.message);
});
I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.
The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.
Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.
New query should look something like:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...
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.
I want to compare date from MongoDB and my date.
Also i read this and this post and I did not find an answer.
My Code :
today: function() {
var today = moment().format();
return Posts.find({createdAt : { $gte : today}}) // show posts created in "future" , so this function must return nothing
},
createdAt = moment().format();// in MongoDB
As a result this construction doesn't work, but if i compare lie this :
var today = moment().format();
var daystart = moment().startOf('day').format();
if (daystart > today){
console.log ("YES");
}
else if (daystart < today)console.log ("NO");
Return
"NO"
Anybody help ?
EDIT :
today: function() {
var today = moment().toDate();
var daystart = moment().startOf('day').toDate();
// console.log(today + daystart);
return Posts.find({createdAt : { $gt : today}})
},
week: function() {
var today = new Date();
return Posts.find({createdAt : { $lt : today}})
},
month: function() {
var today = new Date();
return Posts.find({createdAt : { $ne : today}})
}
createdAt = new Date();
The .format() method is a display helper function which returns the date string representation based on the passed token argument. To compare the date from MongoDB with the the current date and time, just call moment() with no parameters, without the .format() method and get the native Date object that Moment.js wraps by calling the toDate() method:
today: function() {
var now = moment().toDate();
return Posts.find({createdAt : { $gte : now }});
}
Convert date to MongoDB ISODate format in JavaScript using Moment JS
MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.
If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.
var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
console.log("Next day -- " + (reqDate.getDate() + 1))
var d = new Date();
d.setDate(reqDate.getDate() + 1);
var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
You can pass today and tomorrow object to MongoDB queries with new Date() shell method.
MongoClient.connect(con, function (err, db) {
if (err) throw err
db.collection('orders').find({ "order_id": store_id, "orderDate": {
"$gte": new Date(today), "$lt": new Date(tomorrow)}
}).toArray(function (err, result) {
console.log(result);
if (err) throw err
res.send(result);
})
})
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();
}
}
}
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.