Mongoose !findOne - javascript

Why is it that my first statement always returns false when I make up a code that doesn't exist in the "Courses" collection?
// POST /api/my/courses
app.post('/api/my/courses', function(req, res) {
let courseCode = req.body.courseCode.toUpperCase();
let status = req.body.status;
if (!Courses.findOne({ courseCode })) {
res.status(404).send({ "message": "Course not found." })
} else {
let course = new MyCourses({
courseCode: courseCode,
status: status
});
course.save(function(err) {
if(err) return console.error(err);
});
res.status(201).send({ "message": "New course added." });
}
});

You should await for findOne and save as they both return promises. Or, you can also pass in a callback function to findOne as the 2nd argument.
Refer to this

Related

How to check if mongoose array has particular element inside object or not?

Basically what i am trying to do is-
getting comments and foreach comment getting its commentVote
getting the commentVote, checking if votes array inside each commentVote contains postedBy property or not also inlucdes loggedin
user id inside postedBy property
my controller -
exports.getComments = (req, res) => {
const { featureId } = req.params;
Comment.find({ feature: featureId })
.populate("postedBy", "_id username")
.sort({ createdAt: -1 })
.exec((err, comments) => {
if (err) {
return res.status(400).send({
error: errorHandler(err),
});
}
let commentsArray = comments;
commentsArray.forEach((comment) => {
CommentVote.findOne({ comment: comment._id }).exec(
(err, commentvote) => {
if (err) {
return res.status(400).send({
error: errorHandler(err),
});
}
console.log("commentvote.votes", commentvote.votes.length);
const votes = commentvote.votes;
const test = commentvote.votes.includes("req.auth._id");
console.log(test);
});
}
);
});
});
};
I am wondering if i can get true or false on console.log(test);
because based on that i will send response to that particular comment
That particular comment is liked or not!

Why I still get the 200 response status code instead of 404?

I just making delete query to mysql with sequelize.
const model = require('../../../config/model/index');
const controller = {};
controller.drop = async function(req, res) {
try {
await model.activitys.destroy({
where: {
id: req.params.id
}
})
check_id = model.activitys.findAll({
where: {
id: req.params.id
}
})
if(check_id!=null){
res.status(200).json({
status: "Success",
message: "Success",
data: {}
})
}else{
res.status(404).json({
status: "Not Found",
message: `Activity with ID ${id} Not Found`,
data: {}
})
}
} catch (error) {
res.status(404).json({
status: "Error",
message: error.message
})
}
}
module.exports = controller;
I want to delete the data on DB from id parameters, it's work for deleting the data. But when I try to delete by id that not exist in my DB, it's still get the 200 status code.
How to make that will return 404 status code if there's no data exists in DB ?
If you want to check if a single record exists in DB then use findOne or findByPk instead of findAll. findAll always returns an array (either empty or not) and that means it's always not equal to null:
check_id = model.activitys.findOne({
where: {
id: req.params.id
}
})

MongooseError: Query was already executed: Todo.updateOne({ _id: new ObjectId("612df063a8f

I updated mongoose to latest version (6.0.2) and now I'm recieving this error and crush the application whenever .updateOne() is executed. But object update inside the database. My code:
async(req,res) => {
await Todo.updateOne(
{_id : req.params.id},
{
$set : {
status : "inactive"
}
},
(updateError) => {
// if updateError exist
if (updateError) {
// print error
printError(updateError);
// response the error
res.status(500).json({
error : "There was a Server Side Error!"
});
} else {
// if error dose not exist
// print message
console.log("|===> 🗂️ Data Was Updated successfully! 🗂️ <====|\n");
// response success
res.json({
message : "Todo Was Update successfully!"
});
}
});
}
Try to add .clone() to de updateOne function
async(req,res) => {
await Todo.updateOne(
{_id : req.params.id},
{
$set : {
status : "inactive"
}
},
(updateError) => {
// if updateError exist
if (updateError) {
// print error
printError(updateError);
// response the error
res.status(500).json({
error : "There was a Server Side Error!"
});
} else {
// if error dose not exist
// print message
console.log("|===> 🗂️ Data Was Updated successfully! 🗂️ <====|\n");
// response success
res.json({
message : "Todo Was Update successfully!"
});
}
}).clone();
}
Latest version of mongoose not duplicate execution
https://mongoosejs.com/docs/migrating_to_6.html#duplicate-query-execution
Since you are using async syntax, put your code in try/catch blok:
async (req, res) => {
try {
await Todo.updateOne({ _id: req.params.id }, { $set: { status: "inactive"}});
res.status(200).json({message: "Todo Was Update successfully!"});
} catch (error) {
res.status(500).json({error:'There was a Server Side Error!'})
}
}
Your async/await should look like this:
async (req,res) => {
try {
const result = await Todo.updateOne(
{_id : req.params.id},
{
$set : {
status : "inactive"
}
},
);
}
console.log('success', result)
res.json({message: "Todo Was Update successfully!", result })
} catch (err) {
console.log('error', err)
res.status(500).json({error:'There was a Server Side Error!'})
}
}

nodejs mongoDB findOneAndUpdate(); returns true even after database is updated

i am working on an Ionic-1 + nodejs + angular application. My mongoDb findOneAndUpdate() function returns true on each call even the first call updates database.
nodejs:
app.post('/booking', function (req, res) {
var collection = req.db.get('restaurant');
var id = req.body.id;
var status = req.body.status;
collection.findOneAndUpdate({status: status, id: id},{$set:{status:"booked"}}, function (e, doc) {
console.log(id, status);
if (e) {
console.log(e);
}
else if(!doc) {
res.send(false);
}
else {
res.send(true);
}
});
});
controller.js
$scope.bookMe = function(id){
var Obj = {status: "yes", id: id};
myService.booking(Obj).success(function(res){
console.log(Obj, "Checking status")
console.log(res);
if (res == true) {
var alertPopup = $ionicPopup.alert({
title: 'Booking Confirm',
template: 'Thanks For Booking'
});
}
else{
var alertPopup = $ionicPopup.alert({
title: 'Error',
template: ' Not available'
});
}
})
};
where i am doing wrong. my DB gets updated but it returns true always on next call.
The documentation about findOneAndUpdate says :
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.
So it's regular behavior you got a doc.
Note:
Since you are checking availability status="yes", Better hard code, instead of getting it from request query/data.
Change the response according to your requirement res.send(true)/ res.send(false).
Following code will work
app.post('/booking', function (req, res) {
var collection = req.db.get('restaurant');
collection.findOneAndUpdate({
status: "yes",
_id: req.body.id
}, {
$set: {
status: "booked"
}
}, function (err, result) {
//Error handling
if (err) {
return res.status(500).send('Something broke!');
}
//Send response based on the required
if (result.hasOwnProperty("value") &&
result.value !== null) {
res.send(true);
} else {
res.send(false);
}
});
});

Calling async function in node.js

I have an async function
async function getPostAsync() {
const post = await Post.findById('id');
// if promise was successful,
// but post with specific id doesn't exist
if (!post) {
throw new Error('Post was not found');
}
return post;
}
I am calling the function with
app.get('/', (req, res) => {
getPostAsync().then(post => {
res.json({
status: 'success',
});
}).catch(err => {
res.status(400).json({
status: 'error',
err
});
})
});
but I just receive
{
"status": "error",
"err": {}
}
I would expect to either get the error Post was not found or some error with the connection or something like that, but the variable err is simply an empty object in my catch statement.
Consider the following:
let e = Error('foobar');
console.log( JSON.stringify(e) )
This outputs {}, much like in your case. That's because errors don't serialize to JSON very well.
Instead, try this:
res.status(400).json({
status : 'error',
err : err.message // `String(err)` would also work
});

Categories

Resources