Unable to delete data from mongoDB - node.js

Im using POSTMAN to delete contact using id and it returns
{
"n": 0,
"ok": 1
}
This is my delete code so far
router.delete('/contact/:id', (req, res, next) => {
contact.remove({ _id: new objectId(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});

You need to pass the _id value as an ObjectID, not a string:
var mongodb = require('mongodb');
router.delete('/contact/:id', (req, res, next) => {
contact.deleteOne({ _id: new mongodb.ObjectID(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});

id !== _id
change :id in your route to :_id and you should be fine.

Related

async function not working, cannot update and upload image

Im working on a function where there is page asking user for a profile picture and some info.
so far thats what i have
router.post('/edit/:id', async function(req, res) {
let user
const id = req.params.id
try{
user = await User.findById(id)
user.firstname= req.user.firstname,
user.lastname= req.user.lastname,
user.religion= req.user.religion,
user.education= req.user.education,
user.language= req.user.language,
user.lookingfor=req.body.lookingfor,
user.preferEdu=req.user.preferEdu,
user.preferReligion= req.user.preferReligion,
user.bio= req.user.bio
if (req.file != null && req.file !== '') {
await upload(req, res, (err) => {
if(err){
console.log(err)
} else {
if(req.file == undefined){
console.log('no file')
} else {
console.log(req.file)
User.findByIdAndUpdate({_id: id}, {$set: {
imageurl: req.file.location
}}, {new: true}, (err, result) => {
res.redirect('/dashboard')
})
}
}
})
}
} catch{
if (user != null) {
console.log ('no user')
} else {
res.redirect('/dashboard')
}
}
})
the page just jump back to '/dashboard' without anything being saved
before i have a function that just handle upload images, and it was sucessful
router.post('/edit/:id', function(req, res) {
const id = req.params.id
upload(req, res, (err) => {
if(err){
console.log(err)
} else {
if(req.file == undefined){
console.log('no file')
} else {
console.log(req.file)
User.findByIdAndUpdate({_id: id}, {$set: {
imageurl: req.file.location
}}, {new: true}, (err, result) => {
res.redirect('/dashboard')
})
}
}
});
});
I can see the image was uploaded to amazon s3 and req.file.location was logged in the console. but it was not saved in my mongo database.
any help will be appreciated! thanks
you have to use capital letter of 'l' of location. You should switch the line req.file.location to req.file.Location. S3 return json with keys having a captial letter as initials.
Hope, this helps! let me know if that works!

Express app.put / app.post outputs null values

I'm really new to node/express/mongoDB coding, and I have a slight problem with adding/updating values into mongoDB via node/express.
app.post('/', (req, res, next) => {
let data = {
first_value: req.body.first_value,
second_value: req.body.second_value,
};
dbase.collection("testDB").insertOne(data, (err, result) => {
if (err) {
console.log(err);
}
res.send('data added successfully');
});
});
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne({ _id: id }, {
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
app.put does not alter the values in DB, and app.post only adds "null" into every section of the new entry when I'm trying them with Postman. When I add new values with html form, the data is added correctly.
What is the problem with my code?
For app.post , can you provide me a screen shot of the way you are entering data and in which format e.g. , application/raw , application/x-www-form-urlencoded etc .
For app.put you need to correct the following things . The corrected code is as below ,
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne( id , { // put "id" instead of "{ _id: id }"
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
Hope you can get the point and this works for you .

find and modify obejct in mlab collection by _id with nodejs

i am posting an object to update the current one. Searching by id and replacing it. For some reason i don't get errors but the mlab object is not updated. Am i missing something?
app.post("/api/updateCheck", function (req, res) {
console.log('updating', req.body);
conn.collection("checks").findAndModify({
_id: req.body._id
}, {$set: req.body}, {}, function(err,doc) {
if (err) { console.log(err) }
else { console.log("Updated"); }
});
});
got it. updateOne seems to work. I am posting a check object and retrieving id from it to search the collection and update content accordingly.
// modify content
app.post("api/updateCheck", function(req, res) {
console.log("updating", req.body);
conn.collection("checks").updateOne(
{
_id: new ObjectId(req.body._id)
},
{
$set: {
content: req.body.content
}
},
function(err, doc) {
if (err) {
console.log("error", err);
} else {
console.log('success', doc.modifiedCount);
console.log('??', doc.matchedCounted);
res.status(200).json(res.body);
}
}
);
});

How to delete Element In MongoDB property's array with MongooseJS?

I cannot remove an element inside of an array that is a property of a MongoDB Model.
Please remember this is a NodeJS module mongooseJS and not the real MongoDB so functionalities are not the same..
GOAL: Delete an object from the statusLiked array. | I have also confirmed that the value of status.id is correct.
Model:
Const userSchema = new mongoose.Schema({
myStatus: Array,
statusLiked: Array,
)};
Delete:
1. Deletes the status(works). 2. Delete the status from User.statusLiked(no work).
exports.deleteStatus = (req, res, next) => {
var CurrentPost = req.body.statusid; // sends in the status.id
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
// vvvv this vvv
User.update( {id: req.user.id}, { $pullAll: {_id: CurrentPost }, function(err) { console.log('error: '+err) } });
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
};
What happens: The specific status(object) is deleted from the database. But the status still remains in the User.statusLiked array.
What I want to happen: Status to be deleted from the User.statusLiked array and the status to be deleted from the database. Then, reload the page and display a notification.
I got it to work somehow. Working code:
exports.deleteStatus = (req, res, next) => {
var CurrUser = req.body.userid;
var CurrentPost = req.body.post;
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
console.log('meeee'+CurrentPost+'user: ' +CurrUser);
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
User.update(
{ _id: new ObjectId(CurrUser)},
{ $pull: { myStatus : { _id : new ObjectId(CurrentPost) } } },
{ safe: true },
function (err, obj) {
console.log(err || obj);
});
};

Cannot display value from Mongodb on my Jade page

I have the following route :
app.get('/dashboard', passportConf.isAuthenticated, userController.getBoardsCount,userController.getSharedBoardsCount, userController.getBoards);
This is the middleware code I'm using to get my values from MongoDB:
exports.getBoardsCount = function(req, res, next) {
var count = 0;
Room.count({
"owner": req.user._id
}, function(err, count) {
if (err) {
console.log(err);
}
if (count) {
req.count = count;
}
next();
console.log(count);
})
};
exports.getSharedBoardsCount = function(req, res, next) {
var sharedBoards = 0;
Room.count({
$and: [{"owner": {$ne: req.user._id}},{ users : req.user._id}]
}, function(err, sharedBoards) {
if (err) {
console.log(err);
}
if (sharedBoards) {
req.sharedBoards = sharedBoards;
}
next();
console.log(sharedBoards);
})
};
I can display the count on my jade file by using #{count}, but the sharedBoards is not appearing although it is being displayed in the terminal. I used #{sharedBoards} to display it in my Jade file. Can you guys please help me with this? I can't seem to find what is wrong.
exports.getBoards = function(req, res) {
Room.find({
users: req.user._id
}, function(
err,
rooms) {
if (err) {
return err;
}
res.render('account/dashboard', {
rooms: rooms,
count:req.count,
sharedBoards:req.sharedBoards
});
});
};
I mispelled sharedBoards.

Resources