How to perform search in Node.js MongoDB - node.js

I am trying to perform search on my list in node js and my code below is subjected to that,
exports.searchlistbyfirstname = function (req, res) {
var params = req.params;
var record= db.collection('profile');
record.find( { $text: { $search: params.id} }, (err, result) => {
if (err){ return console.log(err)
}
if(result){
response = {status:'success',data:result};
} else{
response = {status:'fail'};
}
res.send(response);
});
};
I am trying to search firstname and I am sure I got wrong.
can anyone please help me

You can try this query to get your firstname
record.find({
firstname: {
$regex: params.id
}
}, (err, result) => {
if (err) {
return console.log(err)
}
if (result) {
response = {
status: 'success',
data: result
};
} else {
response = {
status: 'fail'
};
}
res.send(response);
});

To perform text search ensure first you have created text index for search field.
like:
db.collection('profile').createIndex( { firstName: "text" } );
then you can perform text search on that filed(s).
// params.id should be like "shaishab"
// but better to use req.query.firstName instead of req.params.id
// and you should change your route for that
record.find({$text: {$search: params.id}}, (err, result) => {
if (err) {
console.log(err)
return res.status(400).send({status: 'fail', error: err});
}
if (result) {
response = {status: 'success', data: result};
} else {
response = {status: 'fail'};
}
res.send(response);
});
Or without create text index you can search firstName by using $regex operator
record.find({firstName: { $regex: req.params.id, $options: 'i' } }, (err, result) => {
if (err) {
console.log(err)
return res.status(400).send({status: 'fail', error: err});
}
if (result) {
response = {status: 'success', data: result};
} else {
response = {status: 'fail'};
}
res.send(response);
});

Related

Can't see where multiple call of res caused the error : Cannot set headers after they are sent to the client

I'm following a tutorial in the net. It's a MERN project with mongo/mongoose. When I have implemented the update function in the controller the following error has occured :
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I've seen the answers about similar issue where they say it's because there are 2 or multiple calls of res (res.json(), res.send() etc..), but I don't see where must I change this in the following function :
module.exports.updateUser = async(req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send("ID unknown : " + req.params.id);
try {
await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
},
(err, docs) => {
if (!err)
return res.send(docs);
if (err)
return res.status(500).send({ message: err });
}
)
} catch (err) {
return res.status(500).json({ message: err });
}
};
It may be that you've mixed up two different error handling patterns.
You don't need try/catch if you're using built in error handling of findOneAndUpdate()
await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
},
(err, docs) => {
if (!err)
return res.send(docs);
if (err)
return res.status(500).send({ message: err });
}
)
and if you are using try/catch, you don't need findOneAndUpdate's error handling:
try {
const user = await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
})
return res.send(user)
} catch (err) {
return res.status(500).json({ message: err });
}
Could you please change code like this:
module.exports.updateUser = async(req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send("ID unknown : " + req.params.id);
try {
const result = await UserModel.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
bio: req.body.bio
}
});
return res.send(result);
} catch (err) {
return res.status(500).json({ message: err });
}
};

Sending a POST request in Postman set to send a certain status sends the default status

I want that my POST request sends a HTTP 409 in a certain case, so this is the code:
res.status(409).send();
However, when I tun the request in Postman it shows the result 200 OK. I put some logs in the code and I'm sure that the above line is hit.
What is wrong?
UPDATE:
Here is the full method:
app.post('/orders/:order_id/sync_status', (req, res) => {
order.findOne({ order_id: req.params.order_id},
function(err, results) {
if (err) {
res.send(`error: ${error}`);
} else if (!results) {
res.send(`no order with order_id: ${req.params.order_id}`);
} else {
status.findOne({ order_id: req.params.order_id},
function(err, result) {
if (err) {
res.send(`error: ${error}`);
} else if (result) {
res.status(409).send();
} else {
const newStatus = new status (req.body);
newStatus.save();
}
});
}
res.end();
});
});
and the Postman request:
The simple reason is because you have res.end()
The longer answer is because res.end() is executed before this piece
status.findOne({order_id: req.params.order_id}, function(err, result) {
if (err) {
res.send(`error: ${error}`);
} else if (result) {
res.status(409).send();
} else {
const newStatus = new status(req.body);
newStatus.save();
}
});
got executed due to asynchronous call/callback.
Without testing, your final code should look like this
app.post('/orders/:order_id/sync_status', (req, res) => {
order.findOne({order_id: req.params.order_id}, function(err, results) {
if (err) {
return res.send(`error: ${error}`);
}
if (!results) {
return res.send(`no order with order_id: ${req.params.order_id}`);
}
status.findOne({order_id: req.params.order_id}, function(err, result) {
if (err) {
return res.send(`error: ${error}`);
}
if (result) {
return res.status(409).send();
}
const newStatus = new status(req.body);
newStatus.save();
return res.end();
});
});
});

why my updateOne mongodb does not return anything?

I have this code:
MongoClient.connect(config.mongoURL, {useNewUrlParser: true}, (err, db)=> {
if (err) {
console.log("Err", err)
cb(-1)
}
else {
var con = db.db('englishAcademy')
try {
con.collection("sound").updateOne({"_id": new ObjectID(sndId)}, {
$set: {
"snd_title": info.snd_title,
"snd_type": info.snd_type,
"snd_url": info.snd_url,
"snd_lsnId": info.snd_lsnId,
"snd_lvlId": info.snd_lvlId,
"snd_order": info.snd_order
}
}), (err, doc) => {
console.log("result")
if (err) {
console.log(err)
cb(-1)
}
else {
console.log(doc)
let result = 'row affected'
cb(doc)
}
}
}
catch (e) {
console.log(e)
}
}
})
could anyone please tell me what is wrong with my code?the updateOne function does not return anything.but my mongo database gets updated.
EDIT :
I have done this so far and it did not worked.could anyone please help?I used assert no success.I used new :true, no success.I used finde and update ,no success
let infor = {
"adm_name": info.adm_name,
"adm_username": info.adm_username,
"adm_password": info.adm_password
}
con.collection("admins").findOneAndUpdate({"_id": new ObjectID(admId)}, {
$set: infor
},{new:true} ), (err , result) => {
console.log("result")
if (err) {
console.log(err)
assert.equal(err, null);
cb(-1)
}
else {
let result = 'row affected'
assert.equal(1, result.result.n);
}
set new: true
MongoClient.connect(config.mongoURL, {useNewUrlParser: true}, (err, db)=> {
if (err) {
console.log("Err", err)
cb(-1)
}
else {
var con = db.db('englishAcademy')
try {
con.collection("sound").updateOne({"_id": new ObjectID(sndId)}, {
$set: {
"snd_title": info.snd_title,
"snd_type": info.snd_type,
"snd_url": info.snd_url,
"snd_lsnId": info.snd_lsnId,
"snd_lvlId": info.snd_lvlId,
"snd_order": info.snd_order
},{new: true}
}), (err, doc) => {
console.log("result")
if (err) {
console.log(err)
cb(-1)
}
else {
console.log(doc)
let result = 'row affected'
cb(doc)
}
}
}
catch (e) {
console.log(e)
}
}
})
Try this way ..
collection.findOneAndUpdate(
{"_id": new ObjectID(sndId)},
$set: yourData },
{ new: true },
function (err, documents) {
res.send({ error: err, result: documents });
}
);
Now you can return newData in cb.

Return in json more than one result from query

can someone tell me how Can I response from this query, count() and list of products in one result??
Because at this moment its only return me Array with limit, i want count() without limit, of all products:
Array [ Object, Object, Object, Object, Object ]
router.get('/products', function (req, res) {
var size = parseInt(req.query.pageSize);
if (req.query.pageNumber == 1) {
var page = 0;
} else {
var page = parseInt(req.query.pageNumber) * req.query.pageSize - req.query.pageSize;
}
Product.count()
.exec(function (err, products) {
if (err) {
res.status(404).json({
message: 'Can not download this list'
})
} else {
Product.find().skip(page).limit(size)
.exec(function (err, products) {
if (err) {
res.status(404).json({
message: 'Can not download this list'
})
} else {
res.json(products);
}
})
}
})
});
you can do it in this way :
res.json({ "key1": value1, "key2": value2})

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