how to find records between two dates in typeOrm - find

I am trying to find the records in the past week in typeOrm, I write the following codes, but only get the records as empty array
static async oneWeek(request: Request, response: Response, next: NextFunction) {
let orders = []
try {
orders = await OrderController.repo.find({
where: {
createdAt: Between(
new Date(2023,2,8),
new Date(2023,2,15)
)
}
})
console.log(orders)
} catch (e) {
return response.status(400).send(new Err(HttpCode.E400, ErrStr.ErrNoObj))
}
return response.status(200).send(new Err(HttpCode.E200, ErrStr.OK, orders))
My Order entity has the createdAt column,
#Column()
#CreateDateColumn()
createdAt: Date
#Column()
#UpdateDateColumn()
updatedAt: Date
Except using the exact dates, can I use the date now minus a week to get the records? I tried, but it didn't work since I was not sure what the correct syntax was.

Related

TypeORM returns empty array when querying MongoDB for date

I have the following query that is supposed to get the objects that have a future hospitalizedUntil date from my MongoDB:
return await this.hospitalRepository.find({
where: {
hospitalizedUntil: MoreThanDate(new Date(), EDateType.Datetime)
}
});
Where MoreThanDate:
const MoreThanDate = (date: Date, type: EDateType) => MoreThan(format(date, type));
However, this query doesn't return any objects, even though there is an object in the Mongo where hospitalizedUntil is in the future:
(Current datetime: 2020-08-28T17:11:09.888Z)
[
Hospital {
_id: 5f492efd50e81f63dc60c5d3,
discordId: 'xxxxxxxxxxxxxxxxx',
hospitalizedUntil: 2020-08-28T18:51:17.627Z,
reason: 'Was robbed',
hospitalizedBy: 'xxxxxxxxxxxxxxxxx'
}
]
I've also tried to use the Between operator:
where: {
hospitalizedUntil: Between(new Date(), new Date('9999-12-31'))
}
But this also returned an empty array.
Had the same issue, and solved it by using the native mongoDB query.
hospitalizedUntil: { $gte: format(new Date(), EDateType.Datetime) }
I think those functions just don't work on mongoDB (although I've not found anything related to that issue)

Using TTL in MongoDB [duplicate]

I have a very certain thing i want to accomplish, and I wanted to make sure it is not possible in mongoose/mongoDB before I go and code the whole thing myself.
I checked mongoose-ttl for nodejs and several forums and didn't find quite what I need.
here it is:
I have a schema with a date field createDate. Now i wish to place a TTL on that field, so far so good, i can do it like so (expiration in 5000 seconds):
createDate: {type: Date, default: Date.now, expires: 5000}
but I would like my users to be able to "up vote" documents they like so those documents will get a longer period of time to live, without changing the other documents in my collection.
So, Can i change a TTL of a SINGLE document somehow once a user tells me he likes that document using mongoose or other existing npm related modules?
thank you
It has been more than a year, but this may be useful for others, so here is my answer:
I was trying accomplish this same thing, in order to allow a grace period after an entry deletion, so the user can cancel the operation afterwards.
As stated by Mike Bennett, you can use a TTL index making documents expire at a specific clock time.
Yo have to create an index, setting the expireAfterSeconds to zero:
db.yourCollection.createIndex({ "expireAt": 1 }, { expireAfterSeconds: 0 });
This will not affect any of the documents in your collection, unless you set expireAfterSeconds on a particular document like so:
db.log_events.insert( {
"expireAt": new Date('July 22, 2013 14:00:00'),
"logEvent": 2,
"logMessage": "Success!"
} )
Example in mongoose
Model
var BeerSchema = new Schema({
name: {
type: String,
unique: true,
required: true
},
description: String,
alcohol: Number,
price: Number,
createdAt: { type: Date, default: Date.now }
expireAt: { type: Date, default: undefined } // you don't need to set this default, but I like it there for semantic clearness
});
BeerSchema.index({ "expireAt": 1 }, { expireAfterSeconds: 0 });
Deletion with grace period
Uses moment for date manipulation
exports.deleteBeer = function(id) {
var deferred = q.defer();
Beer.update(id, { expireAt: moment().add(10, 'seconds') }, function(err, data) {
if(err) {
deferred.reject(err);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
Revert deletion
Uses moment for date manipulation
exports.undeleteBeer = function(id) {
var deferred = q.defer();
// Set expireAt to undefined
Beer.update(id, { $unset: { expireAt: 1 }}, function(err, data) {
if(err) {
deferred.reject(err);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
You could use the expire at clock time feature in mongodb. You will have to update the expire time each time you want to extend the expiration of a document.
http://docs.mongodb.org/manual/tutorial/expire-data/#expire-documents-at-a-certain-clock-time

Amazon DynamoDB: How to search for range of dates?

I have a DynamoDB and some items there have a date field. The date field is a string of the format {YYYY-MM-DD}. What should I have to write that the DB will retrieve all items which date field is between a start date and an end date?
This is my code:
function searchFile(from_date, until_date) {
AWS.config = new AWS.Config({accessKeyId: '***', secretAccessKey: '***', region: '***'});
var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
var params = {
"TableName" : '***',
FilterExpression: "Date_ = :date",
ExpressionAttributeValues: {
// What should I write here?
},
}
dynamodb.scan(params, function(err,data) {
if (err) {
console.log(err);
}
console.log(data);
})
}
The DynamoDB stores dates as String. You can use BETWEEN operator to get the range of dates.
createdate - is the attribute name
FilterExpression: "createdate BETWEEN :date1 and :date2",
ExpressionAttributeValues: {
":date1": "2010-05-05",
":date2": "2011-10-04",
}
Date S (string type). The Date values are stored as ISO-8601 formatted
strings.
BETWEEN : Greater than or equal to the first value, and less than or
equal to the second value.

Sails JS - Waterline ORM - Query Date only, not Time

Looking to query against the date only anyone encountered this?
Sample code:
////MODEL
module.exports = {
attributes: {
date: {
type: 'date',
required: true
}
}
};
////CONTROLLER
var today = moment().toISOString();
var queryObj = { date: today };
var newDay = { date: today };
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
Obviously this creates a new record on each refresh, as the iso string will change with each passing second.
Thanks for the help!
Instead of querying for a single date, you can query for a date range that includes all of today. First, you'll need to actually create values for that range--I whipped this up using Moment, but there's probably a better way:
var begin = moment(moment().format("YYYY-MM-DD")).toISOString();
var end = moment(moment().format("YYYY-MM-DD")).add(1, 'days').toISOString();
Then you can use query operators to search the range:
var queryObj = {date: {'>=': begin, '<': end}};
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
As always, be mindful of time zone issues!

Is it possible to extract only embedded documents from a Model in Mongoose?

I'd like to run a query on a Model, but only return embedded documents where the query matches. Consider the following...
var EventSchema = new mongoose.Schema({
typ : { type: String },
meta : { type: String }
});
var DaySchema = new mongoose.Schema({
uid: mongoose.Schema.ObjectId,
events: [EventSchema],
dateR: { type: Date, 'default': Date.now }
});
function getem() {
DayModel.find({events.typ : 'magic'}, function(err, days) {
// magic. ideally this would return a list of events rather then days
});
}
That find operation will return a list of DayModel documents. But what I'd really like is a list of EventSchemas alone. Is this possible?
It's not possible to fetch the Event objects directly, but you can restrict which fields your query returns like this:
DayModel.find({events.typ : 'magic'}, ['events'], function(err, days) {
...
});
You will still need to loop through the results to extract the actual embedded fields from the documents returned by the query, however.