Filter function for req.query - node.js

at the moment i have this:
router.get('/contatos',function(req,res){
if(req.query.nome){
Contato.find({ nome: req.query.nome }, function (err, contato) {
console.log(contato);
if (JSON.stringify(contato) == "[]") {
return res.status(404).json({ Error: "that contact doesn't exist" });
}
if (err) {
return res.status(500);
}
return res.send(contato);
});
}
if(req.query.email){
Contato.find({ email: req.query.email }, function (err, contato) {
if (!contato) {
return res.status(404).json({ Error: "that contact doesn't exist" });
}
if (err) {
return res.status(500);
}
return res.send(contato);
});
}
if(Object.keys(req.query).length === 0){
Contato.find(function (err, contatos) {
if (JSON.stringify(contatos) == "{}") {
return res.status(404).json({ Error: "there are no contacts" });
}
if (err) {
return res.status(500);
}
return res.send(contatos);
}).populate('emergencia');
}
if(!req.query.nome && !req.query.email){
return res.status(400);
}
});
as you guys can see, the mongo query is almost the same the only thing that changes are the values that i pass, so to change this i tried to do a function like this:
function filtro(campo,valor,req,res){
if(arguments[0] != "undefined" && arguments[1] != "undefined"){
// i pass no parameters to filtro so here i just get all values
}
else{
Contato.find({campo:valor},function(err,contatos){
if(err){
return res.status(500);
}
return res.send(contatos);
});
}
}
then above in the first code i placed i just replace the mongo data with the return filtro("email",req.query.email)
AND
return filtro("nome",req.query.nome)
i want to know if what i am doing is correct, i just miss something because on postman it doesn't give me any response it keeps loading

To simplify it a little, you could do something like....
router.get('contatos', function(req, res){
var query = {};
if(req.query.nome) query.nome = req.query.nome;
if(req.query.email) query.email = req.query.email;
Contato.find(query, function (err, contato) {
if(err) return res.json({status : 500, error : err});
if(!contato) return res.json({status : 404, error : "Contact not found"});
return res.json(contato);
});
}

Related

TypeError: categoriesService.createCatergry is not a function

I have this problem in this part of my code
the curse that I study with there is no problem with the teacher I also search a lot
on this code is the controller of the API that I try to build
exports.create = (req, res, next) => {
upload(req, res, function (err) {
if (err) {
next(err)
}
else {
const path = req.file != undefined ? req.file.path.replace(/\\/g, '/') : "";
var model = {
categoryName: req.body.categoryName,
categoryDescription: req.body.categoryDescription,
categoryImage: path != "" ? '/' + path : ''
}
categoriesService.createCatergry(model, (error, results) => {
if (error) {
return next(error)
}
else {
return res.status(200).send({
message: 'Success',
data: results
})
}
})
}
})
}
that the code in service file
async function createCategory(parmas, callback) {
if (!parmas.categoryName) {
return callback({
massage: 'Category name is required'
},
""
);
}
const model = new category(parmas);
model.save().then((response) => {
return callback(null, response);
}).catch((error) => {
return callback(error);
})
}
when I click on it say remove unsend function
Please check if it's not misspelled createCatergry

Generate new username available, always getting Undefined

I have a function to generate an available username, but always return undefined. I tried in many ways, in this case is a recursive function, but I'm always getting the same result, can you help me? Thanks
This is the code:
function generateNewUsernameAvailable(userName, number){
console.log('FUNCTION generateNewUsernameAvailable '+userName+' with number '+number);
User.countDocuments({ 'userName' : userName+number }, (err, count) => {
if (err) {
return `Error: ${err}`;
}
if (count == 0) {
return userName+number;
}else{
generateNewUsernameAvailable(userName, number+1);
}});
}
module.exports.existsUserName = function(req,res){
let userName = req.body.userName;
console.log('POST existsUserName '+userName);
User.countDocuments({ 'userName' : userName }, (err, count) => {
if (err) {
return res.status(500).send({message: `Error: ${err}`});
}
// Available
if (count == 0){
return res.status(200).send();
} else {
// Generate and return a new username available
console.log(generateNewUsernameAvailable('ricardo', 1));
res.status(400).send({message: 'newUsernameAvailable (Example ricardo1)'});
}
})
}
FindOne is faster than countDocuments/estimatedDocumentCount in this case. Both are promises, I'm going to add a possible solution:
function generateNewUsernameAvailable(userName, number){
return User
.findOne({ 'userName' : userName+number })
.then(function(result){
if (result){
return generateNewUsernameAvailable(userName, number+1);
}else{
return userName+number;
}
})
.catch(function(err) {
console.log(`Error: ${err}`);
throw err;
});
}
module.exports.existsUserName = function(req,res){
let userName = req.body.userName;
console.log('POST existsUserName '+userName);
User.countDocuments({ 'userName' : userName }, (err, count) => {
if (err) {
return res.status(500).send({message: `Error: ${err}`});
}
if (count == 0){
return res.status(200).send();
} else {
generateNewUsernameAvailable(userName,1)
.then(function(results){
return res.status(400).send({message: results});
})
.catch(function(err){
return res.status(500).send({message: `Error: ${err}`});
});
}
})
}

How to find a record and insert the same record in Mongoose?

Here I want to get a record and I need to insert the same record with slight modification. But I can't see the data in my new record which I found in my get record. Here is what I tried, can anyone help me? I think the problem is with this line var institution = new Institution(data);:
Institution.find({_id:i._id}).exec(function (err, result) {
if(result)
transferData(result);
}
});
});
}
function transferData(data){
var institution = new Institution(data);
institution.name = 'xxxx';
institution.save(function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
});
}
find() returns an array of docs that match the criteria in the callback hence the line
var institution = new Institution(data);
will not work as it's expecting a Document not an array.
You could use findById() method as:
Institution.findById(i._id).exec(function (err, result) {
if (result) transferData(result);
});
function transferData(data) {
var institution = new Institution(data);
institution.name = 'xxxx';
institution.save(function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
});
}
A much better approach would involve the findByIdAndUpdate() method:
Institution.findByIdAndUpdate(i._id, {name: 'xxxx'}, {upsert: true}, function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
);

Not working with method "UPDATE" in API REST MEAN + Mongoose

exports.updateUsuarioByEmail = function (req, res) {
console.log('updateUsuarioByEmail');
console.log("PARAM ID" + req.params.email);
return Usuario.find({ email: req.params.email }, function(err, usuario) {
if(!usuario) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
if (req.body.email != null) usuario.email = req.body.email;
if (req.body.password != null) usuario.password = req.body.password;
if (req.body.listaCardsSorting != null) usuario.listaCardsSorting = req.body.listaCardsSorting;
return usuario.save(function(err) {
if(!err) {
console.log('Updated usuario');
return res.send({ status: 'OK', usuario:usuario });
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
res.send(usuario);
});
});
};
The error after to execute is :
I believe that the error is the line "return usuario.save(function(err)..."
find return an Array (list of documents) . you can't do save on an array object. Instead try findOne if your email field is unique.
findOne returns a single document, so you can save that.
Replace
Usuario.find({ email: req.params.email }, function(err, usuario)
with :
Usuario.findOne({ email: req.params.email }, function(err, usuario)
To update a model it's much easier to use the findOneAndUpdate() update API. The method finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed.
The syntax is:
Model#findOneAndUpdate([conditions], [doc], [options], [callback])
Parameters:
[conditions] <Object> - the query to match
[doc] <Object> - the document to update
[options] <Object> - update options
[callback] <Function> - callback
For example, the above function can be re-written to use the findOneAndUpdate() method as:
exports.updateUsuarioByEmail = function (req, res) {
console.log('updateUsuarioByEmail');
console.log("PARAM ID" + req.params.email);
var doc = {},
conditions = { "email": req.params.email },
options = { "new": true };
if (req.body.email != null) doc.email = req.body.email;
if (req.body.password != null) doc.password = req.body.password;
if (req.body.listaCardsSorting != null)
doc.listaCardsSorting = req.body.listaCardsSorting;
Usuario.findOneAndUpdate(
conditions,
doc,
options,
function(err, usuario) {
if(!err) {
console.log('Updated usuario');
return res.send({
status: 'OK',
usuario: usuario
});
} else {
if(err.name == 'ValidationError') {
res.statusCode = 400;
res.send({ error: 'Validation error' });
} else {
res.statusCode = 500;
res.send({ error: 'Server error' });
}
console.log('Internal error(%d): %s',res.statusCode,err.message);
}
}
)
};
Here remained the solution:
exports.updateUsuarioByEmail = function (req, res) {
console.log('updateUsuarioByEmail');
return Usuario.findOne({email: req.params.email}, function (err, usuario) {
usuario.email = req.body.email || usuario.email;
usuario.password = req.body.password || usuario.password;
usuario.listaCardsSorting = req.body.listaCardsSorting || usuario.listaCardsSorting;
return usuario.save(function (err) {
if (!err) {
console.log('Updated');
return res.send({status: 'OK', usuario: usuario});
} else {
if (err.name == 'ValidationError') {
res.statusCode = 400;
res.send({error: 'Validation error'});
} else {
res.statusCode = 500;
res.send({error: 'Server error'});
}
console.log('Internal error(%d): %s', res.statusCode, err.message);
}
res.send(usuario);
});
});
};

Value not being updated in DB, node.js and mongoose

I am trying to update the value of my model and it does not work.
The weird thing is that I am printing out the result and it looks different than what I see in my database by using Robomongo.
Any thoughts why this happens?
Here is my code:
exports.create = function(req, res) {
var productId = req.query.product;
if (productId) {
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price =! 0 )
request.status = 'ready';
console.log(request);
(Here I see in the terminal: status = ready)
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});
} else {
var pages = require('../../schemas/wizard/request')();
res.render('requests/form', {
title: 'Make a Request',
pages: pages,
saveState: false
});
}
};
When I am checking the database status is still on pending.
You're changing the status property, but you're not saving the document back to the database after doing so:
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price !== 0) {
request.status = 'ready';
request.save(function(err) { // <-- save it back to the database
if (err) {
console.log('oh no! error', err);
} else {
console.log(request);
}
});
}
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});

Resources