express/mongodb: Value not entering the database through $push - javascript

I'm trying to push a value to mongodb when a route is accessed. When i try it pushing through Mongo Shell, the value is pushed, but when i go to the route, nothing is pushed. The route is something like this
router.post('/course/:userid/step-four/:courseid', function(req, res) {
Course.findOne({
"_id": req.params.courseid
}, function(err, course) {
if (err) {
res.send(err);
} else {
User.update({
"_id": ObjectId(req.params.userid)
}, {
$push: {
courseId: req.params.courseid
}
});
Note that i'm able to retrieve both url params when i log them in console, but somehow it is not entering into the db. What can i do?

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

MongoDB - findOne using the params id results in an empty object or an error

I'm learning Express/Mongo(using mLab) by building a simple little app that I can create a list of clients and a single client detail page.
localhost:3000/clients renders the entire collection of 'clients'
localhost:3000/clients/:id should render the specific client by id
This is a collection: clients entry example from MongoDB (mLab):
{
"_id": {
"$oid": "57ba01d3ab462a0aeec66646"
},
"name": "ClientName",
"address": {
"street": "StreetName",
"city": "Cityname",
"state": "Statename",
"zip": "1234"
},
"createDate": {
"$date": "2016-08-21T19:32:35.525Z"
}
}
I successfully created an href on the /clients page with the id value that links to the specific client:
<%= client.name %>
Which correctly results in this:
http://localhost:3000/clients/57ba01d3ab462a0aeec66646
Here is my get function for /clients/:id:
app.get('/clients/:id', (req, res) => {
db.collection('clients').findOne(req.params.id, (err, result) => {
if (err) {
handleError(res, err.message, "Failed to get clients.");
} else {
console.log(result);
res.render('client.ejs', {client: result})
}
});
})
Clicking on the link results in the following error:
MongoError: query selector must be an object at
Function.MongoError.create
(/Users/username/Desktop/node/node_modules/mongodb-core/lib/error.js:31:11)
at Collection.find
[...]
I've been reading and searching all afternoon and trying a ton of different options like:
'You need to create an ObjectID': https://stackoverflow.com/a/10929670
'You need to use Mongoose to create the ObjectID': https://stackoverflow.com/a/30652361
Do I really need Mongoose? This seems like a foundational thing to do it Mongo — why isn't it working?
you need to use an object : {id: req.params.id}
app.get('/clients/:id', (req, res) => {
db.collection('clients').findOne({_id: req.params.id}, (err, result) => {
if (err) {
handleError(res, err.message, "Failed to get clients.");
} else {
console.log(result);
res.render('client.ejs', {client: result})
}
});
})
You need to convert req.params.id to MongoObject and then use it:
var id = new ObjectID(req.params.id);
Maybe something like:
db.collection('clients').findOne({"_id.$oid": req.params.id}, (err, result) =>

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

mongoose "Find" with multiple conditions

I am trying to get data from my mongoDB database by using mongoose filters. The scenario is that each user object in the database has certain fields like "Region" or "Sector".
Currently I am getting all the users that contain the keyword "region" in there object like so:
// Filter all healthcare bios by region
app.get('/user',function(req, res) {
// use mongoose to get all users in the database
User.find({region: "NA"}, function(err, user)
{
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
{
res.send(err);
}
// return all todos in JSON format
console.log(user);
res.json(user);
});
});
How can put some conditions in mongoose that it return users that contain both "region" && "Sector" in their objects. Currently its only returning the user which have the region keyword in them.
I have tried using $and operator but I couldn't get it to work.
app.get('/user',function(req, res) {
User.find({region: "NA",sector:"Some Sector"}, function(err, user)
{
if (err)
{
res.send(err);
}
console.log(user);
res.json(user);
});
});
If you want data with either region:"NA" or sector:"Some Sector". you can use $or operator.
User.find({$or:[{region: "NA"},{sector:"Some Sector"}]}, function(err, user)
{
if (err)
{
res.send(err);
}
console.log(user);
res.json(user);
});
If you want results that contain any region or sector as long as both are present at the same time you need the following query in your User.find:
{region: {$exists:true},sector: {$exists:true}}
, is the equivalent of $and as long as you are searching different fields.
const dateBetweenDates = await Model.find({
$or: [
{
$and: [
{ From: { $gte: DateFrom } },
{ To: { $lte: DateTo } },
], // and operator body finishes
},
{ _id: req.user.id},
], //Or operator body finishes
})
For anyone else trying to find with multiple conditions using mongoose, here is the code using async/await.
app.get('/user', async (req, res) {
const user = await User.find({region: "NA",sector:"Some Sector"});
if (user) {
// DO YOUR THING
}
});

MongooseJS Not saving to array properly

I want to append a value into my Mongoose array but my array never seems to update. I do the following:
In my controller, I append an eventName into the array eventsAttending like so:
$scope.currentUser.eventsAttending.push(event.eventName);
$http.put('/api/users/' + $scope.currentUser._id, $scope.currentUser)
.success(function(data){
console.log("Success. User " + $scope.currentUser.name);
});
I try to update the array like so:
// Updates an existing event in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
User.findById(req.params.id, function (err, user) {
if (err) { return handleError(res, err); }
if(!user) { return res.send(404); }
user.markModified('req.body.eventsAttending');
user.save(function (err) {
if (err) { return handleError(res, err);}
return res.json(200, user);
});
});
};
But my array never seems to update. I've also tried the following:
// Updates an existing event in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
User.findById(req.params.id, function (err, user) {
if (err) { return handleError(res, err); }
if(!user) { return res.send(404); }
var updated = _.merge(user, req.body);
updated.markModified('eventsAttending');
updated.save(function (err) {
if (err) { return handleError(res, err);}
return res.json(200, user);
});
});
};
With this approach, my array updates properly, but when I try to perform the http put after one time, I get an error saying Error: { [VersionError: No matching document found.] message: 'No matching document found.', name: 'VersionError' }
Here is my UserSchema:
var UserSchema = new Schema({
name: String,
username: String,
eventsAttending: [{ type: String, ref: 'Event'}],
});
If anyone could help that would be much appreciated.
My guess is the object returning from _.merge is no longer a Mongoose model and some information is getting lost in the transform. I would try manually setting all of the fields coming from the request and use events.attending.push() to add to the array, then saving the updated object and see what happens.
Your first example with markModified looks wrong. Looking at the documentation it should be the name of the field that is modified and it appears that you've put the source location for it.
user.markModified('user.eventsAttending')
However that should not be necessary if you use the push method as Mongoose overrides the built-in array function to track changes.

Categories

Resources