bulkCreate records using sequelize in nodejs - node.js

Any way to do a bulk update, create using sequelize and postgres?
I have tried the following:
sequelize.models.Location.bulkCreate(updatedPost.locations,
{ ignoreDuplicates: true }).then(function (locations) {
res.send(updatedPost);
res.end();
});
I got this error:
postgres does not support the 'ignoreDuplicates' option.

INSERT ... ON CONFLICT DO NOTHING/UPDATE is a thing on Postgres now. They have really good documentation. So you could do Sequelize.query() to do it.
But I'm sorry Sequelize still does not support it natively. You have to write a method on your model to do it.

Related

Is there a way to auto create a databse in typeORM?

I am migrating from sequelizeORM to typeORM. In sequelize-cli there are nice commands to drop database and create a new one for example:
node_modules/.bin/sequelize db:drop
node_modules/.bin/sequelize db:create
node_modules/.bin/sequelize db:migrate
Ok, for typeORM I know how to run migration but I can't find anywhere how to automatically create or drop a database. Tnx in advance.
you can use the CLI tool typeorm schema:drop or if you want to drop and recreate the database on each startup, you can use
{
...
dropSchema: true,
...
"migrations": [
"dist/migrations/**/*.js"
]
}
where you do your connection options and set migrations path, and so forth.
You can also use typeorm-extension package, to create or drop the database specified for the connection, for nearly all database driver.
The package also parses the extra parameter charset and characterSet of the extra parameter (ENV: TYPEORM_DRIVER_EXTRA)
import {createDatabase} from "typeorm-extension";
(async () => {
await createDatabase({ifNotExist: true});
await dropDatabase({ifExist: true});
process.exit(0);
})();
You can also provide the charset and characterSet as properties for the first parameter to the createDatabase() function.
F.e
postgres
createDatabase({ifNotExist: true, characterSet: "UTF8"});
mysql
createDatabase({ifNotExist: true, charset: "utf8mb4_general_ci", characterSet: "utf8mb4"});
If you have any questions or concerns feel free to contact me or contribute to the codebase on Github

Updating Particular field in Nodejs

I wanted to update the field data only ,but my code it adding an object each time i am calling update api.I have gone through many sites and found out updateOne is the method but couldnt end up undersatnding how to implement here.I am quite new to node so any help would be appreciated.
const update=(req,res)=>{
console.log(req);
models.detailsSchema.findByIdAndUpdate(req.body.vehicleId,req.body.data,{new:true}).then((msg,err)=>{
if(err)
res.status(400).json({err})
res.status(200).json({
"resCode":"0000",
"resStatus":"Success",
"resMsg":msg
})
});
}
Looks like you're using Mongoose connected to a MongoDB instance? If that's the case, Schema.findByIdAndUpdate works on the primary key or ObjectId of the record you're trying to update. To make this code work, if my assumptions are correct, change to this:
models.detailsSchema.findByIdAndUpdate(req.body._id, req.body.data, { new:true })
Of course, you're going to want to put in some check to make sure _id is defined if this is a create/update route.

Sequelize bulkCreate updateOnDuplicate for postgresQL?

I know there is no support for updateOnDuplicate for postgresQL by Sequelize sequelize doc, so is there a work around for this?
Can it be implemented via "SQL command".
New sequelize (v5) includes updateOnDuplicate feature for all dialects
Fields to update if row key already exists (on duplicate key update)?
(only supported by MySQL, MariaDB, SQLite >= 3.24.0 & Postgres >=
9.5). By default, all fields are updated.
Check here : Docs
You can use as
model.bulkCreate(dataToUpdate, { updateOnDuplicate: ["user_id", "token", "created_at"] })
There is some work around. See upsert function. When used in Postgresql it creates custom function in database. Unfortunately there is no bulkUpsert, so you either use it in some for-loop or execute raw SQL as suggested here.

Omit query log Sequelize NodeJs

Is it possible to omit a single query log while using Sequelize?
For obvious reason I want to know every query shot by my NodeJs server, but I have one that is tied to a recursive function that works like a printing spooler and it's spamming my server log.
Cheers
Yes, it's possible.
If you want to omit logging from a plain query, use this code:
sequelize
.query('SELECT ...', null, {
logging: false
});
If you want to disable logging when finding an object ORM-style, use this syntax:
Model.findAll({
where: {
id: 123
},
logging: false
});
The official documentation where this information is from can be found at http://docs.sequelizejs.com/en/latest/api/model/#findall.

Database schema with sails.js and sails-postgresql

Is there any way to set database schema with sails-postgresql waterline adapter?
By default postgres adapter allways choose default public schema in database but I want to connect it to another schema.
For example I have database dev, schema test in database dev and table users in schema test.
Now I want to select all data from table users, in sql syntax I can simply write:
SELECT * FROM test.users
How to make it work in sails ?
When I write a model that uses postgres adapter, method Users.find() will look for the table users in default public schema. I want to change it to look in schema test without interactions with my postgres database.
Is it possible?
There is support for this, although it is as-yet undocumented. You can set the schema name for a model using the meta.schemaName property, eg:
module.exports = {
tableName: 'users',
meta: {
schemaName: 'test'
},
attributes: {
...
}
};
Update
It turns out this functionality was essentially broken for several versions, but it has been revamped and released in Sails-Postgresql v0.11.0. The syntax is the same as above. The main caveat is that it will not work with multiple Waterline models sharing the same tableName.
It appears that this is a bit buggy on the latest 1.0.3 version, but I found a way to accomplish it, by doing :
postgresql: {
adapter: require('sails-postgresql'),
url: 'postgresql://postgres:blablabla#localhost:5432/simplerp',
schemaName: 'radius',
}
On your config/datastores.js file.
Peace, out!

Resources