Swapping rows for a column that has unique constraint - node.js

I'm using postgresql and sequelize to do my db operations
Suppose I have a person table like this:
id (pkey) | name | email (unique) | company
1 | john | john#x.com | abc
2 | mary | mary#y.com | abc
3 | will | NULL | xyz
I make the unique constraint like this:
const PersonData = sequelize.define(
'users',
{
....
email: {
type: Sequelize.STRING,
allowNull: false,
unique: {
args: true,
msg: 'Email already in use!',
},
},
....
},
I'm getting payload like
{{
id: 1,
email: mary#y.com
},
{
id: 2,
email: john#x.com
}}
I want to swap the emails for id 1 and id 2 here. How can I do that using sequelize?
The output I want:
id (pkey) | name | email (unique) | company
1 | john | mary#y.com | abc
2 | mary | john#x.com | abc
3 | will | NULL | xyz

Related

How to get each comments of different document as separate in mongoDB?

I am creating a social web using Node js and mongoDB. I have three tables as events, projects and reactions(like, comment).
Every event has many projects and every project has many reactions.
events
|----|---------|-------------|
| id | title | description |
|----|---------|-------------|
| e1 | event 1 | |
| e2 | event 2 | descc |
| e3 | event 3 | |
|----|---------|-------------|
projects
|----|-----------|-------------|----------|
| id | project | description | event_id |
|----|-----------|-------------|----------|
| p1 | project 1 | sample | e1 |
| p2 | project 2 | sample | e1 |
| p3 | project 3 | sample | e1 |
| p4 | project 1 | sample | e2 |
|----|-----------|-------------|----------|
reactions
|----|----------|------------|----------|--------|-------|
| id | user_id | project_id | event_id | type | value |
|----|----------|------------|----------|--------|-------|
| 1 | user1 | p1 | e1 | comment| nice |
| 2 | user1 | p1 | e1 | comment| wow |
| 3 | user2 | p1 | e1 | like | 1 |
| 4 | user2 | p1 | e2 | comment| good |
| 5 | user1 | p2 | e1 | comment| nice |
| 6 | user3 | p1 | e1 | comment| nice |
| 7 | user4 | p1 | e1 | like | 1 |
| 8 | user4 | p1 | e1 | comment| bad |
| 9 | user5 | p2 | e1 | comment| enjoy |
| 10 | user3 | p2 | e1 | comment| happy |
|----|----------|------------|----------|--------|-------|
my code
try
{
const id = req.params.id;
var ObjectId = require('mongodb').ObjectID;
if(!ObjectId.isValid(id))
{
return res.status(503).json("Invalid ID");
}
var aggregate = Event.aggregate();
aggregate.match({"_id":ObjectId(id)})
.lookup({ from: "pojects", localField: "_id", foreignField: "event_id",as: "project_doc"})
.lookup({from: "user_reactins", localField: "_id", foreignField: "event_id", as: "reactions"})
.lookup({from: "user_reactins", localField: "project_doc._id", foreignField: "project_id", as: "pro_reactions"})
.addFields({"project_doc.totalComments": "$pro_reactions"})
.project({_id:"$_id",title:"$title", project_doc:"$project_doc",
total_like_event: {
"$size": {
$filter: {
input: "$reactions",
as: "s",
cond: {
$eq: ["$$s.key", "like"]
},
}
}
},
total_comment_event: {
"$size": {
$filter: {
input: "$reactions",
as: "s",
cond: {
$eq: ["$$s.key", "comment"]
},
}
}
}
})
var options = {}
Event.aggregatePaginate(aggregate, options, function(err, results, pageCount, count)
{
return res.status(200).json({data:results[0],pro_status:statusResult,eve_status:eveResult,eve_cat:categoryResult});
})
}
catch (err)
{
return res.status(500).json(err);
}
this is my end point http://url/api/events/e1
If I used this end point, I want all comments for the given event(e1) by categorized by project as follows
{
"data": {
"_id": "e1",
"title": "event 1",
"project_doc": [
{
"_id": "p1",
"title": "project 1",
"description": "sample",
"totalComments": [
{
"_id": "1",
"user_id": "user1",
"programme_id": "p1",
"key": "comment",
"value": "nice",
},
{
"_id": "2",
"user_id": "user1",
"programme_id": "p1",
"key": "comment",
"value": "wow",
},
{
"_id": "6",
"user_id": "user3",
"programme_id": "p1",
"key": "comment",
"value": "nice",
},
{
"_id": "1",
"user_id": "user1",
"programme_id": "p1",
"key": "comment",
"value": "nice",
}
]
},
],
"total_view_event": 0,
"total_like_event": 1,
"total_comment_event": 4
}
}

"query" count posts for each category expressjs mongoose

i am new at MERN stack
i tried to write this query but i can't and search a lot on google without any solution
i have to table one for posts and the second for categories
table 1 posts
--------------------------
|id | title | category |
--------------------------
| 1 | title1 | 1 |
| 2 | title2 | 2 |
| 3 | title3 | 1 |
| 4 | title4 | 1 |
=================
table 2 categories
---------------
|id | name |
---------------
| 1 | cat1 |
| 2 | cat2 |
====================
the results i want is this
---------------------------------
|id | name | number of posts |
---------------------------------
| 1 | cat1 | 3 |
| 2 | cat2 | 1 |
if it's can a help i write this query in mysql
SELECT categories.*,COUNT(posts.id) AS np FROM `categories` JOIN materials ON (categories.id = posts.category) GROUP BY categories.id
and thank you
You can try below aggregation in mongodb 3.6 and above
db.collection.aggregate([
{ "$lookup": {
"from": "posts",
"let": { "id", "$id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$category", "$$id"] }}},
{ "$count": "count" }
],
"as": "count"
}},
{ "$project": {
"name": 1,
"numberOfPosts": { "$arrayElemAt": ["$count.count", 0] }
}}
])

Why use association in sequelize orm?

I made some api system with nodejs.
Also I use sequelize(version 4) for communicates with MySQL.
Below is my model structure.
[user]
no(PK)
userid
userpw
[article]
no(PK)
subject
content
writer(FK to user's userid)
I made with sequelize orm define like this.
import Sequelize from 'sequelize';
const sequelize = new Sequelize('db', 'user', 'pw', {
host: '127.0.0.1',
dialect: 'mysql'
})
const User = sequelize.define('user', {
no: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
userid: {
type: Sequelize.STRING(30),
allowNull: false,
unique: true
},
userpw: {
type: Sequelize.STRING(30),
allowNull: false
}
}, {
freezeTableName: true,
timestamps: true,
underscored: true
});
const Article = sequelize.define('article', {
no: {
type: Sequelize.INTEGER,
primaryKey: true
},
subject: {
type: Sequelize.STRING(50),
allowNull: false
},
content: {
type: Sequelize.STRING(100),
allowNull: false
},
writer: {
type: Sequelize.STRING(30),
references: {
model: 'user',
key: 'userid'
}
}
}, {
freezeTableName: true,
timestamps: true,
underscored: true
})
sequelize.sync({
force: true
});
export default { User, Article };
In Article model, I define write and refer to User's userid.
So Article's writer column is Foreign Key refer to User's userid.
Because If user was deleted, related article have to delete.
Run that code, table will be created and structure is like this.
mysql> desc user;
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| no | int(11) | NO | PRI | NULL | auto_increment |
| userid | varchar(30) | NO | UNI | NULL | |
| userpw | varchar(30) | NO | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
mysql> desc article;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| no | int(11) | NO | PRI | NULL | |
| subject | varchar(50) | NO | | NULL | |
| content | varchar(100) | NO | | NULL | |
| writer | varchar(30) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
After do that, I searched more information about association in sequelize orm.
And I found that sequelize has many association like hasMany, BelongsTo, 'hasMany`, ...
So I add User.hasMany(Article); to my previous code and run it, it add more columns.
mysql> desc article;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| no | int(11) | NO | PRI | NULL | |
| subject | varchar(50) | NO | | NULL | |
| content | varchar(100) | NO | | NULL | |
| writer | varchar(30) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
| user_no | int(11) | YES | MUL | NULL | |
+------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
user_no column was added.
I think it automatically added by hasMany function.
But in my case, I do not have to create user_no, Because I already refer to User's user_id column.
Overall, my question is:
I think I do not have to set hasMany in my case. Is it right?
Why ORM offer assocation function? Just for convenience? or Is there any reason for it?
Thanks.

nodejs - mongodb $lte and $gte not working with $lookup

I need to get record by price range but the query is working fine in shell but not in nodejs. Here is query:
db.model.aggregate([
{ $match: { make_id: make_id } },
{
$lookup: {
from: 'variants',
localField: '_id',
foreignField: 'model_id',
as: 'variant_list'
}
},
{
$unwind: {
path: '$variant_list',
preserveNullAndEmptyArrays: false
}
},
{$match: {status:1, $and:[{'variant_list.price': {$lte:Number(max_price)}}]}},
{$project: { make_id: 1, model_name: 1, variant_list: '$variant_list'}}
])
I have checked the price in database. it is stored like NumberInt(300000) and in my query i have parsed in integer type like => max_price to Number(max_price).
and it gives me all record which are less than and equal to 300000 but it also gives the record which are less than 400000.
But If i'm not using aggregate framework then it is giving me perfect result:
db.model.find({status:1, $and:[{'variant_list.price': {$lte:Number(max_price)}}]})
I dont know why $lte not working perfectly with aggregate and $lookup.
Please Help!!
Updated Sample Collection and Documents
MakeId = a123;
Models:
-----------------------------
mid | makeid | model |
-----------------------------
m1 | a123 | MDLi1 |
m2 | a123 | MDLi2 |
m3 | a123 | MDLi3 |
m4 | a123 | MDLi4 |
m5 | a123 | MDLi5 |
-----------------------------
Variants:
----------------------------------------
vid | modelid | variants | price |
----------------------------------------
v1 | m1 | VARi1 | 150000 |
v2 | m1 | VARi2 | 250000 |
v3 | m1 | VARi3 | 300000 |
v4 | m1 | VARi4 | 350000 |
v5 | m1 | VARi5 | 380000 |
v6 | m2 | VARi6 | 250000 |
v7 | m2 | VARi7 | 280000 |
v8 | m2 | VARi8 | 380000 |
v9 | m2 | VARi9 | 400000 |
v10 | m2 | VARi10 | 450000 |
----------------------------------------
I need to get model detail and variants list by variant price like price range should be between 0 to 300000
My Desire result is :
{
"data": [
{
"makeid": "a123",
"modelid": "m1",
"variant_list": [
{
"variant_id": "v1",
"variant_name": "VARi1",
"price": 150000
},
{
"variant_id": "v2",
"variant_name": "VARi2",
"price": 250000
},
{
"variant_id": "v3",
"variant_name": "VARi3",
"price": 300000
}
]
},
{
"makeid": "a123",
"modelid": "m2",
"variant_list": [
{
"variant_id": "v6",
"variant_name": "VARi6",
"price": 250000
},
{
"variant_id": "v7",
"variant_name": "VARi7",
"price": 280000
}
]
}
]
}

How to Looping inside Model.find Sailsjs

Good day all, can someone suggest me which async function should i use?,
in my case, I need an output the 1st member of each group.
*** note this is just a example of the flow of my program.
/*
Grouplist groupmember
Id | name id | name | group
1 | group1 1 | John | 1
2 | group2 2 | James | 1
3 | group3 3 | Paul | 3
4 | Angel | 2
5 | Anne | 2
6 | Jane | 3
looking for output like this
id | name | group
1 | John | 1
4 | Angel | 2
3 | Paul | 3
*/
var name = [];
Grouplist.find( function(err, grouplist){
for(var x=0;x<=grouplist.length-1; x++){
groupmember.find({id:grouplist[x].id}).limit(1).exec(
function callBack(err,results){
if(err) console.log(err);
name[x] = results.name;
})
}
})
You can get the result in one query using mongodb aggregate operators:
groupmember.aggregate(
[
{
$group:
{
_id: "$group", //grouping key
member: { $first: "$$CURRENT" } //return the first matched document
}
},
{
$project : //project the document to top-level
{
_id: "$member._id",
name: "$member.name",
group: "$member.group"
}
}
],
function(err, members){
console.log(members)
}
)

Resources