How to do query based on "date" column in sqlite3 using sequelize? - node.js

I'm using Sequelize with sqlite3 but having trouble querying data based on "date" type columns.
Here is my model definition:
var sensorData = sequelize.define('Data',
{
time: Sequelize.DATE,
value: Sequelize.FLOAT,
type: Sequelize.STRING,
source: Sequelize.STRING
},
{
timestamps : false
});
Now I want to get all the records with 'time' later than a given time in this function:
function selectData(start_date, num_of_records, callback)
{
sensorData.findAll({
limit: num_of_records,
where: [time, '???'], <====== How to specify the condition here?
order: 'time'}).success(callback);
}
I can't find any thing on Sequelize's website about 'date' type based query statement.
Any idea?

Just like Soumya says, you can use $gt, $lt, $gte or $lte with a date:
model.findAll({
where: {
start_datetime: {
$gte: new Date()
}
}
})

You can use sequelize.fn like this:
where:{timestamp: gte:sequelize.fn('date_format', fromDate, '%Y-%m-%dT%H:%i:%s')
,lte:sequelize.fn('date_format', toDate, '%Y-%m-%dT%H:%i:%s')
}

Related

Sequelize Postgres createdAt time with timezone, saving and getting date and time in a format

image of the user table, createdAt only saving the time and there is no date information with time and timezone fieldI am using sequelize and postgres, when I save a user or value in DB postgres automatically adds createAt and upDatedAt with timestamp, when I retrieve the value of createdAt it gives me "06:15:41.037000+00:00", my question is how to display it in formatted date? Please help me. I tried moment.js to convert but it gives me "Invalid Date" error. I have searched many examples but unable to understand the issue.
this is the response I get when I make api call, but unable to convert the createdAt values to meaningful date as there is no date, only time
i grabbed this quickly from another answer... check out how it was done here
const Test = sequelize.define('test', {
// attributes
name: {
type: DataType.STRING,
allowNull: false
},
createdAt: {
type: DataType.DATE,
//note here this is the guy that you are looking for
get() {
return moment(this.getDataValue('createdAt')).format('DD/MM/YYYY h:mm:ss');
}
},
updatedAt: {
type: DataType.DATE,
get() {
return moment(this.getDataValue('updatedAt')).format('DD/MM/YYYY h:mm:ss');
}
}
I usually create "created_at" and "updated_at" manually in my model and migration rather generated from sequelize and the value of them is sequelize.Date. Here's the code for that :
createdAt: {
type: Sequelize.DATE,
field: 'created_at',
},
updatedAt: {
type: Sequelize.DATE,
field: 'updated_at'
}
and timestamps false to block generate from sequelize
timestamps: false
For MYSQL
You can use sequelize function to get the date only with time cropped
model.findAll({
attributes: [
[sequelize.fn('DATE', sequelize.col('createdAt')), 'DateOnly']
]
})
this will help you get the date only.
For postgres
try to replace the sequelize function by this.
sequelize.fn('date_trunc', 'day', sequelize.col('created'))

Mongoose update or insert many documents

I'm trying to use the latest version of mongoose to insert an array of objects, or update if a corresponding product id already exists. I can't for the life of me figure out the right method to use (bulkWrite, updateMany etc) and I can't can't seem to figure out the syntax without getting errors. For example, i'm trying
Product.update({}, products, { upsert : true, multi : true }, (err, docs) => console.log(docs))
this throws the error DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead. MongoError: '$set' is empty. You must specify a field like so: {$set: {<field>: ...}
and using updateMany just gives me the $set error. I can't seem to find any examples of people using this method, just wondering if somebody can provide me with an example of how to properly use this.
To be clear, I generate an array of objects, then I want to insert them into my db, or update the entry if it already exists. The field I want to match on is called pid. Any tips or advice would be greatly appreciated!
EDIT:
My product schema
const productSchema = new mongoose.Schema({
title : String,
image : String,
price_was : Number,
price_current : {
dollars : String,
cents : String
},
price_save_percent : String,
price_save_dollars : String,
price_save_endtime : String,
retailer : String
})
const Product = mongoose.model('Product', productSchema)
an example of the products array being passed
[
{
title: 'SOME PRODUCT',
image: '',
price_was: '139.99',
price_current: { dollars: '123', cents: '.49' },
price_save_percent: '12%',
price_save_dollars: '16.50',
price_save_endtime: null,
pid: 'VB78237321',
url: ''
},
{ ... },
{ ... }
]
You basically need bulkWrite operation
The array you want to update with
const products = [
{
title: 'SOME PRODUCT',
image: '',
price_was: '139.99',
price_current: { dollars: '123', cents: '.49' },
price_save_percent: '12%',
price_save_dollars: '16.50',
price_save_endtime: null,
pid: 'VB78237321',
url: ''
}
]
The query for bulk update
Model.bulkWrite(
products.map((product) =>
({
updateOne: {
filter: { retailer : product.pid },
update: { $set: product },
upsert: true
}
})
)
)

How do I select a value as a column in sequelize

How do I perform sql query such as this SELECT 'OLD' AS CUSTOM_COLUMN FROM TABLE in sequelize?
You can use sequelize.literal for that.
const response = await YourModel.findAll({
where: {
...attributes
},
attributes: [
'column_name_on_model',
[sequelize.literal("'OLD'"), 'CUSTOM_COLUMN'], //custom column name
],
raw: true
});
If you've set up a model for your table, you can alias the column in the model definition:
{
CUSTOM_COLUMN: {
type: Sequelize.STRING,
field: 'OLD'
}
}
And then limit a find query to that column:
MyModel.find all({ attributes: ['CUSTOM_COLUMN'] })
(See http://sequelize.readthedocs.io/en/v3/docs/models-definition/)

How to find a record using dot notation & update the value in a schema using mongoose

I am using mongoose to perform CRUD operation on my db. This is how my model looks.
var EmployeeSchema = new Schema({
name: String,
description: {
type: String,
default: 'No description'
},
department: [],
lastUpdated: {
type: Date,
default: Date.now
}
});
The department can contains array of object like this.
[
{
"id" : "55ba28f680dec4383eeebf97",
"text" : "Sales",
"topParentId" : "55ba28f680dec4383eeebf8b",
"topParentText" : "XYZ"
},
{
"id" : "55ba28f680dec4383eeebf98",
"text" : "IT",
"topParentId" : "55ba28f680dec4383eeebf8b",
"topParentText" : "XYZ"
},
{
"id" : "55ba28f680dec4383eeebf94",
"text" : "Marketing",
"topParentId" : "55ba28f680dec4383eeebccc",
"topParentText" : "ABC"
}
]
Now I need to find all the employee where department.id = '55ba28f680dec4383eeebf94' and then I need to update the text of the object.
Employee.find({'department.id': '55ba28f680dec4383eeebf94'}, function(err, Employees) {
_.each(Employees, function (emp) {
_.each(emp.department, function (dept) {
if(dept.id === '55ba28f680dec4383eeebf94'){
dept.text = 'XXXXX'; // How to update the employee to save the updated text
}
});
});
});
What is the right way to save the employee with updated text for that department?
Iterating is code is not a "sharp" way to do this. It is better to use the MongoDB update operators, especially since there is no schema defined for the array items here, so no rules to worry about:
Employee.update(
{'department.id': '55ba28f680dec4383eeebf94'},
{ "$set": { "department.$.text": "XXXXX" },
function(err,numAffected) {
// handling in here
}
);
The $set is the important part, otherwise you overwrite the whole object. As is the positional $ operator in the statement, so only the matched ( queried item in the array ) index is updated.
Also see .find**AndUpdate() variants for a way to return the modified object.
I think you can use the update model:
Employee.update({department.id: '55ba28f680dec4383eeebf94'}, {department.text: 'XXXXX'}, {multi: true},
function(err, num) {
console.log("updated "+num);
}
);
First object is the query, what to find: {department.id: '55ba28f680dec4383eeebf94'}, the second one is the update, what to update: {department.text: 'XXXXX'} and the third one is the options to pass to the update, multi means update every records you find: {multi: true}

mongoose subdocument sorting

I have an article schema that has a subdocument comments which contains all the comments i got for this particular article.
What i want to do is select an article by id, populate its author field and also the author field in comments. Then sort the comments subdocument by date.
the article schema:
var articleSchema = new Schema({
title: { type: String, default: '', trim: true },
body: { type: String, default: '', trim: true },
author: { type: Schema.ObjectId, ref: 'User' },
comments: [{
body: { type: String, default: '' },
author: { type: Schema.ObjectId, ref: 'User' },
created_at: { type : Date, default : Date.now, get: getCreatedAtDate }
}],
tags: { type: [], get: getTags, set: setTags },
image: {
cdnUri: String,
files: []
},
created_at: { type : Date, default : Date.now, get: getCreatedAtDate }
});
static method on article schema: (i would love to sort the comments here, can i do that?)
load: function (id, cb) {
this.findOne({ _id: id })
.populate('author', 'email profile')
.populate('comments.author')
.exec(cb);
},
I have to sort it elsewhere:
exports.load = function (req, res, next, id) {
var User = require('../models/User');
Article.load(id, function (err, article) {
var sorted = article.toObject({ getters: true });
sorted.comments = _.sortBy(sorted.comments, 'created_at').reverse();
req.article = sorted;
next();
});
};
I call toObject to convert the document to javascript object, i can keep my getters / virtuals, but what about methods??
Anyways, i do the sorting logic on the plain object and done.
I am quite sure there is a lot better way of doing this, please let me know.
I could have written this out as a few things, but on consideration "getting the mongoose objects back" seems to be the main consideration.
So there are various things you "could" do. But since you are "populating references" into an Object and then wanting to alter the order of objects in an array there really is only one way to fix this once and for all.
Fix the data in order as you create it
If you want your "comments" array sorted by the date they are "created_at" this even breaks down into multiple possibilities:
It "should" have been added to in "insertion" order, so the "latest" is last as you note, but you can also "modify" this in recent ( past couple of years now ) versions of MongoDB with $position as a modifier to $push :
Article.update(
{ "_id": articleId },
{
"$push": { "comments": { "$each": [newComment], "$position": 0 } }
},
function(err,result) {
// other work in here
}
);
This "prepends" the array element to the existing array at the "first" (0) index so it is always at the front.
Failing using "positional" updates for logical reasons or just where you "want to be sure", then there has been around for an even "longer" time the $sort modifier to $push :
Article.update(
{ "_id": articleId },
{
"$push": {
"comments": {
"$each": [newComment],
"$sort": { "$created_at": -1 }
}
}
},
function(err,result) {
// other work in here
}
);
And that will "sort" on the property of the array elements documents that contains the specified value on each modification. You can even do:
Article.update(
{ },
{
"$push": {
"comments": {
"$each": [],
"$sort": { "$created_at": -1 }
}
}
},
{ "multi": true },
function(err,result) {
// other work in here
}
);
And that will sort every "comments" array in your entire collection by the specified field in one hit.
Other solutions are possible using either .aggregate() to sort the array and/or "re-casting" to mongoose objects after you have done that operation or after doing your own .sort() on the plain object.
Both of these really involve creating a separate model object and "schema" with the embedded items including the "referenced" information. So you could work upon those lines, but it seems to be unnecessary overhead when you could just sort the data to you "most needed" means in the first place.
The alternate is to make sure that fields like "virtuals" always "serialize" into an object format with .toObject() on call and just live with the fact that all the methods are gone now and work with the properties as presented.
The last is a "sane" approach, but if what you typically use is "created_at" order, then it makes much more sense to "store" your data that way with every operation so when you "retrieve" it, it stays in the order that you are going to use.
You could also use JavaScript's native Array sort method after you've retrieved and populated the results:
// Convert the mongoose doc into a 'vanilla' Array:
const articles = yourArticleDocs.toObject();
articles.comments.sort((a, b) => {
const aDate = new Date(a.updated_at);
const bDate = new Date(b.updated_at);
if (aDate < bDate) return -1;
if (aDate > bDate) return 1;
return 0;
});
As of the current release of MongoDB you must sort the array after database retrieval. But this is easy to do in one line using _.sortBy() from Lodash.
https://lodash.com/docs/4.17.15#sortBy
comments = _.sortBy(sorted.comments, 'created_at').reverse();

Resources