Save before req.session.destroy() ExpressJS - javascript

I want to save the session value "image location" into the database before I have destroyed the session in logout route
The solution adopted by me is :
app.get('/logout',function(req,res){
Person.update({ username: req.session.user_name }, { $set: {lastimage: req.session.userimage[req.session.img_idx]}}, function(error,update)
{
if(update){
req.session.destroy(function() {
res.end();
});
if(error){
console.log(error);
res.end();
}
}
});
});
But when I am using this get location route the task is accomplished i.e the value in person db is updated but in return there is some weird error shown
TypeError: Cannot read property 'undefined' of undefined
at options.key (/opt/expressjs/app.js:381:94)
at callbacks (/opt/expressjs/node_modules/express/lib/router/index.js:164:37)
at param (/opt/expressjs/node_modules/express/lib/router/index.js:138:11)
at pass (/opt/expressjs/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/opt/expressjs/node_modules/express/lib/router/index.js:173:5)
at Object.router (/opt/expressjs/node_modules/express/lib/router/index.js:33:10)
at next (/opt/expressjs/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at resume (/opt/expressjs/node_modules/express/node_modules/connect/lib/middleware/static.js:65:7)
at SendStream.error (/opt/expressjs/node_modules/express/node_modules/connect/lib/middleware/static.js:80:37)
at SendStream.EventEmitter.emit (events.js:95:17)
Why is it so. I am using ExpressJs sessions and mongodb
P.S: The line /opt/expressjs/app.js:381:94 is
Person.update({ username: req.session.user_name }, { $set: {lastimage: req.session.userimage[req.session.img_idx]}}, function(error,update)

Have you tried saving
'req.session.userimage[req.session.img_idx]' in some var before use ?
for example:
var uName = req.session.user_name,
uImage = req.session.userimage[req.session.img_idx];
Person.update({ username: uName }, { $set: {lastimage: uImage }}, function(error,update) { ...
BTW, you may be calling res.end() twice, which will make things weird.
EDIT:
app.get('/logout', function(req,res) {
var uName = req.session.user_name,
uImage = req.session.userimage[req.session.img_idx];
Person.update({ username: uName }, { $set: {lastimage: uImage }}, function(error,update) {
if(error)
console.log(error);
// This actually destroys the session
delete req.session;
res.end();
});
});

Related

TypeError: callback.apply is not a function (Node.js & Mongodb)

When I add the line "{ upsert: true }", I got this error:
TypeError: callback.apply is not a function
// on routes that end in /users/competitorAnalysisTextData
// ----------------------------------------------------
router
.route('/users/competitorAnalysisTextData/:userName')
// update the user info (accessed at PUT http://localhost:8080/api/users/competitorAnalysisTextData)
.post(function (req, res) {
// use our user model to find the user we want
User.findOne({userName: req.params.userName}, function (err, user) {
if (err) res.send(err);
console.log(
'user.competitorAnalysis.firstObservation: %#',
user.competitorAnalysis.firstObservation,
);
// Got the user name
var userName = user.userName;
// update the text data
console.log('Baobao is here!');
user.update(
{
userName: userName,
},
{
$set: {
'competitorAnalysis.firstObservation': req.body.firstObservation,
'competitorAnalysis.secondObservation': req.body.secondObservation,
'competitorAnalysis.thirdObservation': req.body.thirdObservation,
'competitorAnalysis.brandName': req.body.brandName,
'competitorAnalysis.productCategory': req.body.productCategory,
},
},
{upsert: true},
);
// save the user
user.save(function (err) {
if (err) return res.send(err);
return res.json({message: 'User updated!'});
});
});
});
Without this line, there is no error. I'm new to nodejs, not very sure where the problem is.
Update
No error message now, but this part of the database is not updated with new data. The embedded document is still empty.
// on routes that end in /users/competitorAnalysisTextData
// ----------------------------------------------------
router
.route('/users/competitorAnalysisTextData/:userName')
// update the user info (accessed at PUT http://localhost:8080/api/users/competitorAnalysisTextData)
.post(function (req, res) {
console.log('1');
// Just give instruction to mongodb to find document, change it;
// then finally after mongodb is done, return the result/error as callback.
User.findOneAndUpdate(
{userName: req.params.userName},
{
$set: {
'competitorAnalysis.firstObservation': req.body.firstObservation,
'competitorAnalysis.secondObservation': req.body.secondObservation,
'competitorAnalysis.thirdObservation': req.body.thirdObservation,
'competitorAnalysis.brandName': req.body.brandName,
'competitorAnalysis.productCategory': req.body.productCategory,
},
},
{upsert: true},
function (err, user) {
// after mongodb is done updating, you are receiving the updated file as callback
console.log('2');
// now you can send the error or updated file to client
if (err) return res.send(err);
return res.json({message: 'User updated!'});
},
);
});
There are 2 ways to update documents in mongodb:
find the document, bring it to server, change it, then save it back to mongodb.
just give instruction to mongodb to find document, change it; then finally after mongodb is done, return the result/error as callback.
In your code, you are mixing both methods.
with user.save(), first you search the database with user.findOne, and pull it to server(nodejs), now it lives in your computer memory.
then you can manually change the data and finally save it to mongodb with user.save()
User.findOne({ userName: req.params.userName}, function(err, user) {
if (err)
res.send(err);
//this user now lives in your memory, you can manually edit it
user.username = "somename";
user.competitorAnalysis.firstObservation = "somethingelse";
// after you finish editing, you can save it to database or send it to client
user.save(function(err) {
if (err)
return res.send(err);
return res.json({ message: 'User updated!' });
});
the second one is to use User.findOneAndUpdate().. This is preferred, instead of user.findOne() then user.update(); because those basically searching the database twice. first to findOne(), and search again to update()
Anyway,the second method is telling mongodb to update the data without first bringing to server, Next, only after mongodb finish with its action, you will receive the updated-file (or error) as callback
User.findOneAndUpdate({ userName: req.params.userName},
{
$set: { "competitorAnalysis.firstObservation" : req.body.firstObservation,
"competitorAnalysis.secondObservation" : req.body.secondObservation,
"competitorAnalysis.thirdObservation" : req.body.thirdObservation,
"competitorAnalysis.brandName" : req.body.brandName,
"competitorAnalysis.productCategory" : req.body.productCategory
} },
{ upsert: true },
function(err, user) {
//after mongodb is done updating, you are receiving the updated file as callback
// now you can send the error or updated file to client
if (err)
res.send(err);
return res.json({ message: 'User updated!' });
});
You forgot to pass a callback to the update method
user.update(
{
$set: {
'competitorAnalysis.firstObservation': req.body.firstObservation,
'competitorAnalysis.secondObservation': req.body.secondObservation,
'competitorAnalysis.thirdObservation': req.body.thirdObservation,
'competitorAnalysis.brandName': req.body.brandName,
'competitorAnalysis.productCategory': req.body.productCategory,
},
},
{upsert: true},
function (err, result) {},
);
update method expects 3 arguments.
document update
options
callback

Existing property return undefined

I started the implementation of a RESTful API usin node.js, express, and mongodb. Everything went well until now, I've a route to authenticate an user as follow:
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
nickname: req.body.nickname
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if (user) {
console.log(user);
console.log(user.nickname);
console.log(user.email);
console.log(user.password);
console.log(user.sexe);
if (user.password != req.body.password) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {
var token = jwt.sign(user, app.get('salt'), {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
token: token
});
}
}
});
});
The user is retrieved, and loged in the console as follow:
{ sexe: 'H',
email: 'MrPanda#gmail.com',
password: 'bambou',
nickname: 'MrPanda',
_id: 56cb703e7aef3f83c7dac0a7 }
which is perfect, but then, the three following consol.log return the three following lines:
MrPanda
MrPanda#gmail.com
undefined
H
I see absolutely no reason why the password is undefined at this point, I tried to change the attribute name to 'mdp', same issue... Any ideas ? Thanks
If you are using mongoose it does not return a plain JSON object. It is actually a special mongoose object and may not function how you expect.
You have two options:
Convert the mongoose object to a JSON object.
Add {lean: true} to the Users options parameter.
OR JSON.stringify(user)
OR user.toJSON()
Use the proper get() and set() methods (which you should be doing anyways).
user.get('password')
user.get('email')
user.get('name')
Try that and let me know if it doesn't work still.

MongoDB - Save vs Update for specific fields in document

Using the MEAN stack, I'm attempting to have an admin account update another user's information, in this case, their title/role on the site. The problem I have is that the only function available when editing a user is the save() function. It might be that I can utilize the update function, and if that is the case please let me know, but it doesn't look possible:
The problem arises that when the user is saved, it creates a new document, and overwrites the user's password and salt to some value. I'd like to be able to call an "update" function that will only update the one field, but I can't figure out how to. Is there a way to do this with the save function?
Relevant Code:
exports.updateUserRoles = function(req, res) {
var currUser = req.body;
User.findById(currUser._id, function(err, user) {
//user.roles = currUser.roles;
user.save( { _id : '56467b28ba57d8d890242cfa', roles : 'admin' } );
//THE BELOW WAS A PREVIOUS ATTEMPT
/*user.save( function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(user);
console.log('test2');
}
});*/
});
};
Trying something else that seems very close, but still not quite there yet.
Here's what I'm running:
exports.updateUserRoles = function(req, res) {
var currUser = req.body;
User.findById(currUser._id, function(err, user) {
//user.roles = currUser.roles;
//user.roles.set(0, 'admin');
console.log('test');
user.update(
{ _id: '56467b28ba57d8d890242cfa' },
{
$set: {
roles: 'admin',
},
}
);
console.log('test2');
});
};
Upon hitting the user.update line, we have the user in the local variables, seen:
user.update goes into this Document.prototype.update function, seen:
The args look to be building right, which _id we are targeting and what the action is, seen:
But then after running, nothing seems to change. I'm very much stumped.
For updates various fields in mongodb you can use update with different atomic operators, like $set, $unset, $push etc.
Example:
var updateUserRoles = function(db, callback) {
db.collection('users').updateOne(
{ "_id", : "user_id", },
{ $set: { "password": "new_password" } },
function(err, results) {
console.log(results);
callback();
}
);
};

How to create an update function on nodejs/mongodb?

Hi I am currently new to nodejs and mongodb what I want to do is make a function to update my win,lose,draw record from my userschema.
My Schema:
UserSchema = new mongoose.Schema({
username:'string',
password:'string',
email:'string',
//Change Made
win:{ type: Number, default: 0 },
lose:{ type: Number, default: 0 },
draw:{ type: Number, default: 0 }
});
My Function for updating:
//Update scores
app.post("/user/updateScores", function (req, res) {
var user = new User({
username:req.body.username,
win:req.body.win,
lose:req.body.lose,
draw:req.body.draw
});
Users.findOne({ username : req.params.username }, function(error, user) {
if (error || !user) {
res.send({ error: error });
} else {
user.update(function (err, user) {
if (err) res.json(err)
req.session.loggedIn = true;
res.redirect('/user/' + user.username);
});
}
});
});
The problem is when I try updating, when I try updating via my html file. It does not update anything and just stays the same (the values win,lose,draw the default value is 0 so when I logout and login again the values of the win,lose,draw record is still zero). I thoroughly checked if the problem was the html and javascript functions that I have made but this is not the case so I think that the problem is the update function I have made. Any of you guys have an idea where I went wrong? Thanks!
Assuming your post is being called correctly from the client, you'll need to be careful about variable and parameter names, as the scope right now is that you're saving an exact duplicate of the user object that was just fetched via findOne.
You had user declared as a variable of the post callback, and then again within the findOne. The inner variable user will take precedence.
app.post("/user/updateScores", function (req, res) {
var username = req.body.username;
Users.findOne({ username : username }, function(error, user) {
if (error || !user) {
res.send({ error: error });
} else {
// update the user object found using findOne
user.win = req.body.win;
user.lose = req.body.lose;
user.draw = req.body.draw;
// now update it in MongoDB
user.update(function (err, user) {
if (err) res.json(err) {
req.session.loggedIn = true;
}
res.redirect('/user/' + user.username);
});
}
});
});

What am I doing wrong on my update function on nodejs/mongodb?

Hi I am currently new to nodejs and mongodb what I want to do is make a function to update my win,lose,draw record from my userschema.
My Schema:
UserSchema = new mongoose.Schema({
username:'string',
password:'string',
email:'string',
//Change Made
win:{ type: Number, default: 0 },
lose:{ type: Number, default: 0 },
draw:{ type: Number, default: 0 }
});
var db = mongoose.createConnection(app.get('MONGODB_CONN')),
User = db.model('users', UserSchema);
My Function for updating:
app.post('/user/updateScores',function(req, res){
try{
var query = req.body.username;
User.findOneAndUpdate(query, { win : req.body.win, lose : req.body.lose, draw : req.body.draw }, function (err,user){
if (err) res.json(err) ;
req.session.loggedIn = true;
res.redirect('/user/' + user.username);
});
}
catch(e){
console.log(e)
}
});
The problem is when I try updating, it updates the current data BUT goes to a blank page and throws an exception saying:
ReferenceError: win is not defined
at eval (eval at <anonymous> (C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\underscore\underscore.js:1176:16), <anonymous>:5:9)
at template (C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\underscore\underscore.js:1184:21)
at Function.exports.underscore.render (C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\consolidate\lib\consolidate.js:410:14)
at C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\consolidate\lib\consolidate.js:106:23
at C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\consolidate\lib\consolidate.js:90:5
at fs.js:266:14
at Object.oncomplete (fs.js:107:15)
but I already defined win properly, what seems to be the problem?
User.update(
{username:req.body.username},
{ win : req.body.win, lose : req.body.lose, draw : req.body.draw },
function (err, data) { //look - no argument name "user" - just "data"
//2 mistakes here that you should learn to never do
//1. Don't ignore the `err` argument
//2. Don't assume the query returns something. Check that data is not null.
console.log(data);
//The next line must be INSIDE this function in order to access "data"
res.redirect('/user/' + data.username);
});
//ACK don't try to access "data" (or "user") here. this is asynchronous code!
//this code executes EARLIER IN TIME than the User.update callback code
update after your snippet v2
your find call is simply not matching any documents, so user is null
FYI You can do a find and update at the same time with a single findOneAndUpdate operation
User.update({
username: req.body.username
},{
$set: {
win : req.body.name,
loose : req.body.loose
}
}, function(err, result) {
if (err) {
console.log(err);
} else if (result === 0) {
console.log("user is not updated");
} else {
console.log("user is updated");
}
});
I hope you can understand your issue and can update your User collection.

Categories

Resources