Express app.put / app.post outputs null values - node.js

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 .

Related

Editing Large Collection in MongoDB

I am trying to edit an entire collection in my MongoDB Database.
The collection is about 12k documents in size.
I was trying to edit the files from my angular controller
let promises = [];
array.forEach(each => {
promises.push(this.commonService.postObject('editObject', each));
});
forkJoin(promises).subscribe(data =>{})
My node function
module.exports.editObject = (model) =>{
return function (req, res, next) {
model.findOneAndUpdate({
'_id': req.body._id
}, req.body, {
upsert: true
}, function (err, doc) {
if (err) return res.send(500, {
error: err
});
return res.send(req.body);
});
};
}
But I get the error Message
ERR_INSUFFICIENT_RESOURCES
Is there a smarter way to do that?

Err: Cannot POST /api/success

I am trying to send a POST request but it seems like the route isn't working based off the error. However, I get the value of req.body.entries logged in my console so it has to be working. When I send a GET request the browser sits and loads. The same thing happens in Postman. I am trying to figure out why I get an error on the POST request and the GET request sits. Thank you in advance.
index.js
const successRoute = require("./routes/success");
app.use("/api/success", successRoute);
success.js
router.get(
"/",
basicAuth({
users: { username: "password" },
}),
async function (req, res) {
try {
const entry = await Entry.find({});
res.sendStatus(entry);
} catch (err) {
res.sendStatus({ msg: "oops something went wrong" });
}
}
);
router.post("/", async (req, res, next) => {
try {
//console.log(req.body);
const { store, entries } = req.body;
Entry.findOneAndUpdate(
{ _id: store },
{ $set: { entries: +req.body.entries } },
{ new: true },
(err, doc) => {
if (err) {
console.log(err);
}
console.log(req.body.entries);
next();
}
);
} catch (err) {
const entry = new Entry({
_id: store,
entries: req.body.entries,
});
await entry.save();
res.sendStatus(200);
next();
}
});
I think the problem is, inside your router.post(), you're not sending any response, you only call next(). I don't see any next route for the request.
I'd recommend something like this:
router.post("/", async (req, res, next) => {
try {
//console.log(req.body);
const { store, entries } = req.body;
Entry.findOneAndUpdate(
{ _id: store },
{ $set: { entries: +req.body.entries } },
{ new: true },
(err, doc) => {
// throw the error and catch later
if (err)
throw err;
console.log(req.body.entries);
// send response instead of calling next()
res.sendStatus(200);
}
);
} catch (err) {
const entry = new Entry({
_id: store,
entries: req.body.entries,
});
await entry.save();
// send response
res.sendStatus(200);
// next(); // don't call next unless next route defined
}
});

Unable to delete data from mongoDB

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.

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