mongoose doesn't update model by ID - javascript

apiRoutes.put('/intake/:id', function(req, res) {
var id = req.params.id;
Intake.findById({id, function(err, intake) {
if (err)res.send(err);
intake.check = true;
intake.save(function(err) {
if (err) {return res.json({success: false, msg: 'Error'});}
res.json({success: true, msg: 'Successful update check state.'});
});
}})
});
What's problem? In console i see ID, it's ok, but database have no change

Intake.findById(/*remove { here*/id, function(err, intake) {
if (err)res.send(err);
intake.check = true;
intake.save(function(err) {
if (err) {return res.json({success: false, msg: 'Error'});}
res.json({success: true, msg: 'Successful update check state.'});
});
})

You gave us too few information to help you. But I got some hints on how to find out what's going wrong: (I added example code a the end of my answer.)
Use a proper formatting of your code. Mistakes are easier to find.
Please avoid res.send(err). Most express apps provide an error to HTML Page translation at the end of the route pipe. This only works if you call res.next(err);. If your app does not provide error page generating at the end of the pipe then, you could use res.status(400).json({success: false, msg: err.message});.
After the use of res.send or res.next or res.json you have to end the execution of the function by return before one of these functions can be called a second time. This can be very complicated in case of nested or asynchrounous method calls. But in your example it's quite easy.
Use some log outputs to see which part of the code you reach and which not.
console.dir(<object>); prints out the structure of this object.
Hope this helps a little bit. ;-)
apiRoutes.put('/intake/:id', function(req, res)
{
var id = req.params.id;
Intake.findById(id, function(err, intake)
{
if (err)
{
res.next(err);
console.error(err);
return;
}
console.log("Modify check attribute");
intake.check = true;
console.dir(intake);
intake.save(function(err)
{
console.log("Intake save called!");
if (err)
{
console.error(err);
res.json({
success: false,
msg: 'Error'
});
return;
}
console.log("Success");
res.json({
success: true,
msg: 'Successful update check state.'
});
});
}})
});

you can use this
Intake.update({_id: req.params.id},
{
check : true
},
function(err){
if(err){
console.log(err);
res.status(400).send(err.errors);
}else{
res.status(200).end();
}
});

Related

user.save won't run the callback function

I'm trying to save information to my user schema in my database. I'm doing this using "user.save" but for some reason the code within the parenthesis is not run.
user.save(function(err) {
//THIS CODE DOESNT SEEM TO RUN
if (err) {
console.log(err);
} else {
res.json({ message: 'given a reset-token' })
}
//
});
So I switched to the following code since I needed to get a success message from the server:
user.save((err) => {
console.log('hello');
if (err) {
console.log(err);
console.log('err2');
res.status(404).json({ message: 'Save error' });
}
}).then(() => {
res.status(201).json({ message: 'Activated' });
});
Witch successfully sends me the status code when changes to the user have been pushed to the database. Could anyone explain why the second one works and the first one doesn't? And if there is a better way to write this code?

writing a query and return one value from a database in node js and mongoose

im writing a query in node js, my model of schema has 3 objects( userid, tokenid, mediaid), and i want to find the token id of a certain userid and use it in another function.
my code is as below:
app.get('/registeruser/:userid', function(req, res){
var name = req.params.userid;
user.findOne({userid: name},function(err, users1){
if(!users1){
res.send('Error 404, user not found');
return res.status(404).send();
}
else{
var query = user.find({tokenid: 1});
query.where({userid: name});
query.exec(function(err, result){
if(err){
res.send('erooooooor')
}
else{
res.send('okk')
console.log(result)}
});
user is the name of my model.
i run my code and i expect it to return the tokenid but it returns this: []
with these in my database:
userid: 'hgfj1234',
tokenid: 'juiodkdn12345678',
mediaid: ['med10', 'med11']
when i write userid: 'hgfj1234' it gives me this: [] but i want the real tokenid.
if anyone can help me i really appreciate it.
thanks in advance.
You don't need to do additional request to get record from mongodb.
That's enough to use findOne with complex attributes.
Try this:
app.get('/registeruser/:userid', function(req, res) {
var query = {
userid: req.params.userid,
tokenid: {$exists: true, $not: {$size: 0}}
};
user
.findOne(query)
.exec(function(err, User) {
if(err) { // error happen,
console.error(err); // log error
return res.status(500).send({
success: false,
message: 'System error'
}); // respond with 500 status and send json response with success false and message. return will stop execution to go down
}
if(!User) { // response from database was empty or null
return res.status(404).send({
success: false,
message: 'User not found'
}); // respond with 404 status and send json response with success false and message. return will stop execution to go down
}
res.send({
success: true,
tokenid: User.tokenid
}); // and at last everything is ok, we return json response with success and tokenid in response
});
});
attributes in query variable means to request mongodb to give us document with userid defined in request and that has tokenid that is defined and not is empty string (not size 0).
if You still did not getting desired result so check database for existence of necessary document.
If I understand your query right, you will reduce all find() calls to the tokenid with value 1. You will receive only any result, if the user has the token "1".
I suspect you wanted to code a projection, that is the second parameter on find():
var query = user.find({"userid": name});
query.select({"tokenid": 1})
.exec(function(err, result){
if(err){
res.send('erooooooor')
}
else{
res.send('okk')
console.log(result)}
});

async watefall doesn't call the functions

So i am actually woking on a simple program with node.Js and i have an issue using async.waterfall :
I created a function in my user model that connect the user by accessing the database, here is the code :
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
if (err){
callback(err,null);
return;
}
if(res != null ){
// test a matching password if the user is found we compare both passwords
var userReceived = res.items[0].login;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log(userReceived);
callback(null,'done')
}
], function(err){
if (err) {
console.error(err);
}
console.log('success');
});
}
Using node-inspector i figured out that the main issue(I think) is that when it enters the waterfall function it doesn't execute the callback function of findOne it literally skips this and directly jump to the getPassword function (which isn't executed too).
so if someone could help me figuring out what's the problem that would be nice since i'm on it for around two days now.
Thank you
EDIT:
After adding the different missing cases of tests(which was why the callback didn't worked) I have this connection function:
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
console.log('login: ',res.login);
console.log('erreur: ',err);
if (err){
callback(err,null);
return;
}
if(!res)
{
console.log('getLogin - returned empty res');
callback('empty res');
}
if(res != null ){
// test a matching password if the user is found we compare both passwords
var userReceived = res;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log('login received :',userReceived.login);
var Ulogin = userReceived.login;
var Upassword = userReceived.password;
// function that compare the received password with the encrypted
//one
bcrypt.compare(password, Upassword, function(err, isMatch) {
if (err) {
console.log(err);
callback(err,null);
return;
}
else if (isMatch) {
console.log('Match', isMatch);
callback(null,isMatch);
}
else {
console.log('the password dont match', isMatch);
callback('pwd error',null);
}
});
},
], function(err){
if (err) {
console.error('unexpected error while connecting', err);
return false;
}
console.log('connected successfully');
return true;
});
}
And in my main file server.js i'm doing currently doing :
var connect = users.connection(login,password);
//the goal is to use the connect variable to know if the connection
//failed or not but it's 'undefined'
if(connect){
res.send('youyou connecté');
}
else {
res.send('youyou problem');
}
this absolutely don't work so i tried to use Q library but I have an error saying
"TypeError: Cannot read property 'apply' of undefined at Promise.apply"
here is the code using Q:
app.post('/signup', function (req, res) {
var login = req.body.login;
var password = req.body.password;
Q.fcall(users.connection(login,password))
.then(function (connect) {
if(connect){
res.send('connected');
}
else {
res.send('problem');
}
})
.catch(function (error) {
throw error;
})
.done();
});
but i am a little bit astonished i thought that by using async.waterfall() i told the function to wait until it received all the callbacks return so i don't understand why the connect variable is 'undefined'?
What I don't understand is - what was the flow exactly? did 'usersModel.findOne' get called?
What I see that is missing here in the getLogin function is a callback in the case that both the 'if' statement return false. in this case you'll get stuck in the first function and you won't advance to 'getPassword' function.
If this still doesn't work, please try executing the following code and report what was printed:
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
if (err){
console.log('getLogin - error has occured');
callback(err,null);
return;
}
if(!res)
{
console.log('getLogin - returned empty res');
callback('empty res');
}
console.log('getLogin - result seems OK');
// test a matching password if the user is found we compare both passwords
var userReceived = res.items[0].login;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log('getPassword');
console.log(userReceived);
callback(null,'done')
}
], function(err){
if (err) {
console.error(err);
}
console.log('success');
});
}

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.

Node.js, MongDB (Mongoose) - Adding to data retrieved.

I currently have the following code:
User.find({ featuredMerchant: true })
.lean()
.limit(2)
.exec(function(err, users) {
if (err) {
console.log(err);
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
_.forEach(users, function(user){
_.forEach(user.userListings, function(listing){
Listing.find({
user: user
}).populate('listings', 'displayName merchantName userImageName hasUploadedImage').exec(function(err, listings){
user.listings = listings;
});
});
});
res.jsonp(users);
}
});
As you can see I am trying to add the retrieved listings to each 'user' in the 'users' lean object that I have returned. If I do a console.log(user) inside the Listing.find exec method after adding 'user.listings = listings', the result is as I would expect; a user object with a listings property, with this listing property containing all the listings retrieved.
However, if I console.log the 'users' object, the listings for each user cannot be found.
I'm pretty sure I'm doing something stupid here, but I really cannot work out what. Any help would be greatly appreciated. Thank you!
you right about stupid thing !
No offense, I think this is a common mistake :)
_.forEach(users, function(user){
_.forEach(user.userListings, function(listing){
Listing.find({
user: user
})
.populate('listings', 'displayName merchantName userImageName hasUploadedImage')
.exec(function(err, listings){
user.listings = listings;
});
});
});
// Listing.find inside foreach hasn't finish yet
// I suppose it's always an asynchronous call
res.jsonp(users);
Maybe you can fix it using promises. This an example with q library.
var promises = [];
_.forEach(users, function(user){
_.forEach(user.userListings, function(listing){
var deferred = q.defer();
promises.push(deferred);
Listing.find({
user: user
})
.populate('listings', 'displayName merchantName userImageName hasUploadedImage')
.exec(function(err, listings){
user.listings = listings;
deferred.resolve(user);
});
});
});
q
.all(promises)
.done(function(allUsers){
// Do what you want here with your users
res.jsonp(allUsers);
});
Check this and don't hesitate to fix it because I can't test it.
Thank you both for your input. It's truly appreciated. I managed to solve this an easier way which now I come to think of it is pretty obvious - but hey we live and learn. Basically, my 'userListings' model field was an array of Object Id's and I wanted to add the physical listings from the listings model into the data returned. The following code did the trick for me.
exports.findFeaturedMerchants = function(req, res, next) {
User.find({ featuredMerchant: true })
.populate('userListings')
.limit(2)
.exec(function(err, data) {
_.forEach(data, function(user){
Listing.populate(user.userListings, '', function(err, user){
if (err) {
console.log(err);
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
}
});
});
console.log(data);
res.jsonp(data);
});
};
I simply had to populate each userListings object into the user, by using the populate function twice - once for the user and another time for each listing. I was finding it tricky to get my head around - probably because I didn't understand how the populate function worked exactly, but there we go :)
Jamie

Categories

Resources