How can I update value in object with node.js and sequelize - javascript

I would like to update values (missions.status and missions.success) in the object,
but I don't know how to approach it.
"missions": {
"missions": [
{
"week": 1,
"status": "",
"mission": "do something",
"success": ""
}
]
}
I tried to like this.
//success.js
router.put('/:id/result', async (req, res, next) => {
const status = req.body.missions.missions[0].status;
const success = req.body.missions.missions[0].success;
try {
const result = await models.User.findOne({
attribute: ['missions'],
where: {
id: req.params.id,
},
});
const data = {
result: result,
};
let originalData = data.result.dataValues.missions.missions[0];
let weekdata = { status: status, success: success };
let resultData = Object.assign(originalData, weekdata);
res.send({
data: resultData,
message: 'good status changed',
});
} catch (error) {
console.log(error);
res.sendStatus(400);
}
});
It is req.body and response, looks like it works, but doesn't update in databases. I don't know how to save that.
//req.body
{
"missions": {
"missions":[
{
"status": "no",
"success":"success"
}
]
}
}
// res.send
{
"data": {
"week": 1,
"status": "no",
"mission": "do something",
"success": "success"
},
"message": "good status changed"
}

You didn't call update for your model so that's why you'll get no changes in a DB.
Try this:
await models.User.update(weekdata, {
where: {
id: req.params.id,
},
});

Related

Update nested JSONB in postgresql using sequelize

I am using NodeJS to update a nested info in the database but I can't seem to figure this out.
Data in database
{
"id": 1,
"data": {
"__v": 0,
"_id": "5887e1d85c873e0011036889",
"text": "you have to change this text",
"type": "cat",
"used": true,
"user": "5a9ac18c7478810ea6c06381",
"source": "user",
"status": {
"feedback": "",
"verified": true,
"sentCount": 1
},
My code to update:
UpdateFacts: async function (req, res, next) {
const {text} = req.body
const {id} = req.params
if(!id){
return res.status(400).send({message:'please provide id'})
}
if(!Object.keys(req.body).length){
return res.status(400).send({message:'please provide text'})
}
const checkIfFactExist = await Facts.findOne({
where: {
id
}
})
if(!checkIfFactExist){
return res.status(404).send({message:'this id does not exist'})
}
try {
if(text){
checkIfFactExist.data.text = text
}
checkIfFactExist.save()
return res.status(200).send({message:'updated'})
} catch (error) {
return res.status(500).send(error.message)
}
Data is the column and text is the field am trying to change but it's not working.

Sequelize returning null values from database (API problem)

I seem to have a problem with Sequelize .
The thing is i have set an SQL database , when i try to reach it via sequelize (node) it just returns nulled values
[
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
},
{
"id": null
}
]
This is my service,
When i create an object inside the findUsers function and return as if it is real data , it just works
const User = require('../models/User');
const addUser = async (user) => {
try {
await User.create(user)
} catch (e) {
console.log(e);
}
}
const findUsers = async () => {
try {
//return await User.findAll({});
const u = User.findAll();
/*u = {
nom : "lozo",
}*/
return u;
} catch (e) {
console.log(e)
}
}
module.exports = {addUser,findUsers}

How to pass two requests in single API call with Node js - Cloudant

I'm trying to pass two search requests in single API call But here some times I am getting both requests results and some times getting only one request results.
Basically this is my JSON structure in cloudant db:
{
"_id": "123",
"name": "Naveen",
"hoby": "Cricket"
},
{
"_id": "234",
"name": "Varun",
"hoby": "chess"
},
{
"_id": "345",
"name": "Tarun",
"hoby": "Cricket"
},
{
"_id": "456",
"name": "pavan",
"hoby": "chess"
}
Here my requirement would be to get 'hoby' of Cricket 50 members and 'hoby' of Chess 50 members.
For that this is how I am trying currently:
doGet: function(request, response) {
var usersState = [];
var names = { "usersState": usersState, "message": "ok" };
if (!myDb) {
response.json({ "message": "Dataabase connection failed" });
return;
}
var queryForCricket = {
"selector": {
"hoby": "Cricket"
},
"fields": [
"_id",
"name",
"hoby"
],
"sort": [],
"limit": 50,
"skip": 0
};
var queryForChess = {
"selector": {
"hoby": "chess",
},
"fields": [
"_id",
"name",
"hoby"
],
"sort": [],
"limit": 50,
"skip": 0
};
async.parallel(
[
myDb.find(queryForCricket, function (err, body) {
if (!err) {
body.docs.forEach(function (doc) {
if (doc)
usersState.push(doc);
});
response.json(names);
}
}),
myDb.find(queryForChess, function (err, body) {
if (!err) {
body.docs.forEach(function (doc) {
if (doc)
usersState.push(doc);
});
}
})
], function (err, results) {
if (err) {
response.send({ "message": "Read operration failed" });
return;
}
});
}
I have written two queries and passing two through Async call but not getting results properly all the time. So is there any optimised way to handle query part and getting results.
The issue here is your final result depends on execution order of both callbacks of your async.parallel find functions. When the second find finishes first you'll get both results but when the first find finishes first you'll get only results of queryForCricked query.
To get both results you should collect them in the final callback function and use response.json there:
...
async.parallel(
[
myDb.find(queryForCricket, function (err, body) {
if (!err) {
body.docs.forEach(function (doc) {
if (doc)
usersState.push(doc);
});
}
}),
myDb.find(queryForChess, function (err, body) {
if (!err) {
body.docs.forEach(function (doc) {
if (doc)
usersState.push(doc);
});
}
})
], function (err, results) {
if (err) {
response.send({ "message": "Read operration failed" });
return;
}
response.json(names);
}
);
...
While collecting data in the shared usersState array is completely working approach it has flaws. For example, you cannot control the order in which your find data will be inserted. async.parallel gives a better way to collect the data from the functions it's running. You can use callback async.parallel inserts into each function to collect the data in the final callback:
async.parallel(
[
function (cb) { myDb.find(queryForCricket, cb); },
function (cb) { myDb.find(queryForChess, cb); },
], function (err, results) {
if (err) {
response.send({ "message": "Read operration failed" });
return;
}
// result is an array with data from queries: [crickets.body, chess.body]
results.forEach(function (body) {
body.docs.forEach(function (doc) {
if (doc) usersState.push(doc);
});
});
response.json(names);
}
);
...

Deleting Order Items from Orders

I have the following JSON stored in mongodb
[
{
"orderItems": [
"606808d2d7351b0c52d38634",
"606808d2d7351b0c52d38635"
],
"status": "Pending",
"_id": "606808d2d7351b0c52d38636",
"shippingAddress1": "Flowers Street , 45",
"shippingAddress2": "1-B",
"city": "Thessaloniki",
"zip": "00000",
"country": "Greece",
"phone": "+00302410551416",
"user": {
"_id": "6062d46da91a58067da5dfc2",
"name": "Vasilis",
"id": "6062d46da91a58067da5dfc2"
},
"dateOrdered": "2021-04-03T06:18:58.879Z",
"__v": 0,
"id": "606808d2d7351b0c52d38636"
}
]
I can delete the order, no problem with that
router.delete('/:id', (req, res) => {
Order.findByIdAndRemove(req.params.id)
.then((order) => {
if(order) {
res.status(200).json({
success: true,
message: 'The order is deleted'
})
} else {
res.status(404).json({
success: false,
message: 'order not found'
})
}
}).catch((err) => {
return res.status(400).json({
success: false,
error: err
})
})
})
Now I want to change the above code, so as to delete the orderItems as well. how to do that?
Thanks,
Theo
You can use Model.deleteMany to delete the OrderItems (I'm guessing that's the model name) after deleting the Order document. And you don't have to call status(200) on the response object since it's automatically set when calling res.json.
router.delete('/:id', async (req, res) => {
try {
const order = await Order.findByIdAndRemove(req.params.id)
if (!order) {
return res.status(404).json({
success: false,
message: 'Order not found',
})
}
await OrderItem.deleteMany({ _id: { $in: order.orderItems } })
res.json({
success: true,
message: 'Order deleted',
})
} catch (err) {
return res.status(500).json({
success: false,
error: err,
})
}
})

Assign Variables to JSON data in node JS

I have an API End point that i am trying to assign variables to, now the one JSON data is an array and I Loop over it to get the data out in my console log, the difficulty i am having is that i want to assign variables to them.
Here is my code:
const request = require('request');
request('https://fantasy.premierleague.com/api/leagues-classic/1114549/standings/?page_new_entries=1&page_standings=1&phase=1', { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
var data = body.standings.results;
data.forEach(obj => {
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});
console.log('-------------------');
});
});
and here is my JSON data:
{
"league": {
"id": 1114549,
"name": "The crew",
"created": "2020-09-11T17:36:20.083556Z",
"closed": false,
"max_entries": null,
"league_type": "x",
"scoring": "c",
"admin_entry": 3523866,
"start_event": 1,
"code_privacy": "p",
"rank": null
},
"new_entries": {
"has_next": false,
"page": 1,
"results": []
},
"standings": {
"has_next": false,
"page": 1,
"results": [
{
"id": 30771462,
"event_total": 8,
"player_name": "Mohammed Ismail",
"rank": 1,
"last_rank": 0,
"rank_sort": 1,
"total": 8,
"entry": 3808290,
"entry_name": "Moe"
}
Now I am trying to console log only the standings.result.player_name in my console log so i can use it else where, how do i do that
So my output in the console should only be "player_name": "Mohammed Ismail",
I'm not sure that i get the question, but in case if you want to get all player_name and collect it in array as example, You can do it next:
const request = require('request');
const url = 'https://fantasy.premierleague.com/api/leagues-classic/1114549/standings/?page_new_entries=1&page_standings=1&phase=1';
async function getStandings(url) {
return new Promise((resolve, reject) => {
request(
url,
{ json: true },
(err, res, body) => {
if (err) {
reject(err);
return;
}
resolve(body.standings.results);
}
);
});
}
(async () => {
const data = await getStandings(url);
// here you will receive array of stadings
console.log('data : ', data);
})();

Categories

Resources