Why getting error when updating MongoDb? - javascript

I am building backend with MEAN stack, but when I try to update document in the db i am getting an error:
topUp = function(name, amount, callback) {
User.updateOne(
{ "name" : name },
{ $set: { "wallet": amount } },
function(err, results) {
console.log(results);
callback();
});
};
TypeError: User.updateOne is not a function
But e.g. findOne() works fine:
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
i
f (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
//res.json({success: true, info: {wallet: user.wallet, userPic: user.userPic}});
topUp(decoded.name, amount, function() {
User.close();
});
}
});
"User" is a Mongo model file.

I think it's not defined in the database driver that you might be using. I think you are using Mongoose and updateOne() is not available there. You cannot use all native mongodb functions with all drivers

There is an en existing enhancement request for this https://github.com/Automattic/mongoose/issues/3997 , but maybe the findByIdAndUpdate() method could be a close alternative.

Related

How can I use mongoose to delete something in an array using an API?

I'm building a todo app and in the database have an employee document containing 2 arrays (todo & done). The tasks are stored here, and I currently can add tasks to the arrays, but I'm having trouble figuring out how to get my API work to delete them.
Here's what my employee doc looks like
{"_id":{"$oid":"61797a3ed15ad09b88d167ab"},"empId":"1008","password":"password2","firstName":"test","lastName":"user","__v":5,"done":[],"todo":[{"_id":{"$oid":"61870bfe6ac33427b8406f7d"},"text":"testtask","id":"1"}]}
Currently I receive errors when trying to test using SoapUI, many similar to this "TypeError: Cannot read property 'findByIdAndDelete' of undefined" or Cannot DELETE /api/employees/1007/6184645df6bbd93340c0e390
Here's my delete API
*
* Delete task
*/
router.delete("/:empId/tasks/:id", async (req, res) => {
try {
Employee.findByIdAndDelete(
{ _id: req.params.id },
function (err, employee) {
if (err) {
console.log(err);
res.status(500).send({
message: "Internal server error: " + err.message,
});
} else {
console.log(employee);
console.log(
"Task with the id of" +
req.params.id +
" has been deleted successfully"
);
res.json(employee);
}
}
);
} catch (e) {
console.log(e);
res.status(500).send({
message: "Internal server error: " + e.message,
});
}
});
Currently, I can get messages to the console saying it's been deleted but it hasn't actually deleted in the database
Welcome to stackoverflow! You should use updateOne with $pull. Try:
Employee.updateOne({
empId: req.params.empId
}, {
$pull: {
todo: {
_id: req.params.id
}
}
})
Reference: https://stackoverflow.com/a/27917378/9459826
MongoDB docs: https://docs.mongodb.com/manual/reference/operator/update/pull/

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();
}
);
};

mongoDB node.js findAndModify troubles

I am doing an online course about MongoDB which is unfortunately a little out of date. It seems some of the functions have changed (course is using version 1.4 while I am using 3.0.)
Here is the code I am having trouble with, which I have tried to bring up to date with the current version of MongoDB:
app.js
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/course', function(err, db) {
if (err) throw err;
db.collection['counters'].findAndModify({
query: {
name: 'comments'
},
update: {
$inc: {
counter: 1
}
},
new: true
}, function(err, doc) {
if (err) throw err;
if (!doc) {
console.dir('No counter found for comments.');
} else {
console.dir('Number of comments: ' + doc.counter);
}
return db.close();
});
});
If I run the same findAndModify through the Mongo shell I get the anticipated result (increment the counter and display the new document,) but when I run this with node it has no effect on the database and throws this error:
TypeError: Cannot call method 'findAndModify' of undefined
Any tips?
Please try:
db.counters('counters').findAndModify
instead of:
db.collection['counters'].findAndModify
use this now:
db.collection('counters').findOneAndUpdate(
{name: 'comments'}, //query
{$inc: {counter: 1}}, //update
{ //options
upsert: true, // create the doc when it's not there
returnOriginal:false // return the modified doc *(new is not supported here!)
},
function(err, r){ //callback
if(err) throw err;
console.log('counter: '+r.value.counter);
}
);
Whoops, I just had the wrong kind of brackets. Should have had:
db.collection('counters')
instead of
db.collection['counters']
Almost like T_G said.
From the mongodb docs:
Existing collections can be opened with collection
db.collection([[name[, options]], callback);
If strict mode is off, then a new collection is created if not already
present.
So you need to do this:
db.collection('counters', function(err, collection){
collection.findAndModify({
query: {
name: 'comments'
},
update: {
$inc: {
counter: 1
}
},
new: true
}, function(err, doc) {
if (err) throw err;
if (!doc) {
console.dir('No counter found for comments.');
} else {
console.dir('Number of comments: ' + doc.counter);
}
});
});

Categories

Resources