nodejs sequelize map reponse - node.js

I have an API that should return an array, good but my result each array has more than 3 objects so I need to map them and I did it doing it in the back end
async function getAllProduct(req,res) {
try {
const results = await Products.findAll({
// raw: true, <= remove
attributes:['id','name', 'float', 'price'],
include: [{
model: SubCategory,
as: 'subcategory',
attributes: ['id','name'],
},
{
model:Exteriors,
as: 'exteriors',
attributes: ['id','name']
},
{
model:Types,
as: 'types',
attributes: ['id','name']
},
],
})
results.map( (products) => {
const model = {
id: products.id,
name: products.name,
float: products.float,
price: products.price,
id_sub: products.subcategory.id,
subcategory: products.subcategory.name,
id_types: products.types.id,
type: products.types.name,
id_ext: products.exteriors.id,
exterior: products.exteriors.name,
}
listProducts.push(model);
})
if(listProducts){
return res.status(200).json({listProducts})
}
else{
return res.status(400).json({result: 'failed to get Products'})
}
} catch (error) {
console.error(error);
}
}
it would be better to map the result to the front end or already send mapped, and how could I narrow down this path to fetch the data from the front

Related

mongoose findOneAndUpdate gives different user

I was trying to $pull an object inside my cart collections. but after I make a request and sent a specific _id it gives me a different person.
this was the _id I sent from my client side.
{ id: '62a849957410ef5849491b1b' } /// from console.log(req.params);
here's my mongoose query.
export const deleteItem = (req,res) => {
const { id } = req.params;
console.log(id);
try {
if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'ID not found' });
ClientModels.findOneAndUpdate(id, {
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier
}
}
},{
new: true
}).then(val => console.log(val)).catch(temp => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
}
after the request here's the callback.
{
_id: new ObjectId("62a77ab16210bf1afd8bd0a9"),
fullname: 'Gino Dela Vega',
address: '008 Estrella.st santo cristo',
email: 'gamexgaming1997#gmail.com',
google_id: 'none',
birthday: '1997-12-30',
number: 9922325221,
gender: 'Male',
username: 'ginopogi',
password: '$2b$12$YCc1jclth.ux4diwpt7EXeqYyLOG0bEaF.wvl9hkqNVptY.1Jsuvi',
cart: [],
wishlist: [],
toBeDeliver: [],
Delivered: [],
__v: 0
}
as you guys can see after sending a specific _id to find a user...the callback gives me a different user reason that I can't pull the specific object inside cart. (the object I was trying to pull is on another user)
Probably because findOneAndUpdate expect a filter as first parameter, try to switch to findByIdAndUpdate if you want to filter by a specific _id:
export const deleteItem = (req, res) => {
...
ClientModels.findByIdAndUpdate(
id,
{
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier,
},
},
},
{
new: true,
}
)
.then((val) => console.log(val))
.catch((temp) => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
};

Include Model with Group - Sequelize/NodeJS

I have this problem, and i cant solved that.
I need get the name form 'competenciaId' in another model.
const data = await FuncionariosCompetencias.findAndCountAll({
attributes: ['competenciaId',
sequelize.fn('count', sequelize.col('competenciaId'))],
include: [
{ model: Competencia, attributes: [] }
],
group: ['competenciaId', 'Competencia.competencia']
})
.then(function (data) {
return data;
})
.catch(error => {
return error;
});
res.json({ success: true, data: data });
If i removed the "includ:" i have the result but i need name to show it
var Funcionario_Competencias = sequelize.define('funcionarios_competencias', {
nivelcomp: {
type: Sequelize.INTEGER
}
},
{
timestamps: false
})
Funcionario_Competencias.belongsTo(Competencia)
Funcionario_Competencias.belongsTo(Funcionario)

Sequelize - Select on associated table

My problem:
I am creating an route which will return some informations about a group, it has an id, an user assigned and also has some documents. I just want to show how much documents exists, in SQL would be SELECT COUNT, but how can i do this in this in sequelize?
My code:
async list(req, res){
const docGroups = await DocGroup.findAll({
raw: true,
include: [{
model: User,
as: 'userAssigned'
},
{
model: Document,
as: 'Document'
}
]
}).then(groups => {
const result = groups.map(group => {
return Object.assign(
{},
{
id: group.id,
name: group.name,
userAssinged: group['userAssigned.firstName'],
docAmount: // I want to put documents' count here
}
)
})
console.log(groups)
})
}
What is printed in console.log(groups):
[
{
id: 1,
name: 'pleaseworks',
createdAt: 2020-06-10T02:38:11.531Z,
updatedAt: 2020-06-10T02:38:11.531Z,
'userAssigned.id': 1,
'userAssigned.firstName': 'Please',
'userAssigned.lastName': 'Works',
'userAssigned.email': 'pleaseworks#gmail.com',
'userAssigned.password': '$2a$08$3BA4I4dsaQ3lsHy342344b5P41v5eHWjwqv6dve28nSdqbGvhsdS',
'userAssigned.createdAt': 2020-06-10T02:37:29.062Z,
'userAssigned.updatedAt': 2020-06-10T02:37:29.062Z,
'userAssigned.groupId': null,
'Document.id': 2,
'Document.description': 'deowkdopewkdwe',
'Document.content': 'odepodkewokodwe',
'Document.groupId': 1,
'Document.createdAt': 2020-06-10T02:43:46.005Z,
'Document.updatedAt': 2020-06-10T02:43:46.005Z
}
]
If DocGroup has many Document try something like this:
{
model: Document,
attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'docAmount']]
as: 'Document'
}

How to sort by column?

When I sort by role_name column, this error occurs:
column users.role_name does not exist
If sort by any other column, then there will be no problems. How to sort by column for which join is performed?
module.exports.getAll = async function (req, res) {
try {
const query = {
where: {
[Op.or]: [
{
full_name: {
[Op.iLike]: `%${req.query.search}%`
}
},
{
username: {
[Op.like]: `%${req.query.search}%`
}
},
Sequelize.where(Sequelize.col((Roles, "role_name"), "varchar"), {
[Op.like]: `%${req.query.search}%`
})
]
},
include: [{
model: Roles,
attributes: ["role_name"],
required: true
}],
offset: +req.query.pageSize * (+req.query.page - 1),
limit: +req.query.pageSize,
order: [
[req.query.sort, req.query.order]
]
};
const users = await Users.findAndCountAll(query);
res.status(200).json(users);
} catch (e) {
errorHandler(res, e);
}
};
If add to include:
order: [
[Roles, req.query.sort, req.query.order]
]
then it does not work. And if add this after include, it will not be possible to sort by the remaining columns.

mongoDB find, update and pull in One Query

I want to do all the find the data from the collection and then want to update some field as well as depending on want to empty the array.
const addCityFilter = (req, res) => {
if (req.body.aCities === "") {
res.status(409).jsonp({ message: adminMessages.err_fill_val_properly });
return false;
} else {
var Cities = req.body.aCities.split(","); // It will make array of Cities
const filterType = { "geoGraphicalFilter.filterType": "cities", "geoGraphicalFilter.countries": [], "geoGraphicalFilter.aCoordinates": [] };
/** While using $addToset it ensure that to not add Duplicate Value
* $each will add all values in array
*/
huntingModel
.update(
{
_id: req.body.id,
},
{
$addToSet: {
"geoGraphicalFilter.cities": { $each: Cities }
}
},
{$set:{filterType}},
).then(function(data) {
res.status(200).jsonp({
message: adminMessages.succ_cityFilter_added
});
});
}
};
Collection
geoGraphicalFilter: {
filterType: {
type:String,
enum: ["countries", "cities", "polygons"],
default: "countries"
},
countries: { type: Array },
cities: { type: Array },
aCoordinates: [
{
polygons: { type: Array }
}
]
}
But as result, the only city array is getting an update. No changes in filterType.
You appear to be passing the $set of filterType as the options argument, not the update argument.
huntingModel
.update(
{
_id: req.body.id,
},
{
$addToSet: {
"geoGraphicalFilter.cities": { $each: Cities }
},
$set: {
filterType
}
}
).then(function(data) {
res.status(200).jsonp({
message: adminMessages.succ_cityFilter_added
});
});

Resources