updating(PUT) array in express js - javascript

i am using expressjs(nodejs). I am trying to store array data while updating existing data (dealtype & dealprice), but unable to do so.
my existing dataset
{
"_id": "56a59a2923e047bc2128cd99",
"foodImageUrl": "modules/foods/client/img/food.jpg",
"deal": [
{
"_id": "56a59a2923e047bc2128cd9a",
"dealprice": "asd",
"dealtype": "asd"
}
],
"name": "ads",
"created": "2016-01-25T03:44:41.346Z"
}
my expressjs controller
exports.update = function (req, res) {
var food = req.food;
food.name = req.body.name;
food.deal.dealtype = req.body.deal.dealtype;
food.deal.dealprice = req.body.deal.dealprice;
food.foodImageUrl = req.body.foodImageUrl;
food.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(food);
}
});
};

One way to update the existing document. First of all, find the document need to changed by _id or other key word. here is one sample by _id.
Food.findOne({_id: req.food._id}, function(err, food) {
food.name = req.body.name;
food.deal.dealtype = req.body.deal.dealtype;
food.deal.dealprice = req.body.deal.dealprice;
food.foodImageUrl = req.body.foodImageUrl;
food.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(food);
}
});
});
Or just use the findOneAndUpdate to update the existing document.

Related

Using Multiple FindOne in Mongodb

I am trying to extend the amount of fields that our API is returning. Right now the API is returning the student info by using find, as well as adding some information of the projects by getting the student info and using findOne to get the info about the project that the student is currently registered to.
I am trying to add some information about the course by using the same logic that I used to get the project information.
So I used the same findOne function that I was using for Projects and my logic is the following.
I created a variable where I can save the courseID and then I will put the contents of that variable in the temp object that sending in a json file.
If I comment out the what I added, the code works perfectly and it returns all the students that I require. However, when I make the additional findOne to get information about the course, it stops returning anything but "{}"
I am going to put a comment on the lines of code that I added, to make it easier to find.
Any sort of help will be highly appreciated!
User.find({
isEnrolled: true,
course: {
$ne: null
}
},
'email pantherID firstName lastName project course',
function(err, users) {
console.log("err, users", err, users);
if (err) {
return res.send(err);
} else if (users) {
var userPromises = [];
users.map(function(user) {
userPromises.push(new Promise(function(resolve, reject) {
///////// Added Code START///////
var courseID;
Course.findOne({
fullName: user.course
}, function(err, course) {
console.log("err, course", err, course);
if (err) {
reject('')
}
courseID = course ? course._id : null
//console.log(tempObj)
resolve(tempObj)
}),
///// ADDED CODE END //////
Project.findOne({
title: user.project
}, function(err, proj) {
console.log("err, proj", err, proj);
if (err) {
reject('')
}
//Course ID, Semester, Semester ID
//map to custom object for MJ
var tempObj = {
email: user.email,
id: user.pantherID,
firstName: user.firstName,
lastName: user.lastName,
middle: null,
valid: true,
projectTitle: user.project,
projectId: proj ? proj._id : null,
course: user.course,
courseId: courseID
}
//console.log(tempObj)
resolve(tempObj)
})
}))
})
//async wait and set
Promise.all(userPromises).then(function(results) {
res.json(results)
}).catch(function(err) {
res.send(err)
})
}
})
using promise could be bit tedious, try using async, this is how i would have done it.
// Make sure User, Course & Project models are required.
const async = require('async');
let getUsers = (cb) => {
Users.find({
isEnrolled: true,
course: {
$ne: null
}
}, 'email pantherID firstName lastName project course', (err, users) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
let findCourse = (users, cb) => {
async.each(users, (user, ecb) => {
Project.findOne({title: user.project})
.exec((err, project) => {
if (!err) {
users[users.indexOf(user)].projectId = project._id;
ecb();
} else {
ecb(err);
}
});
}, (err) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
let findProject = (users, cb) => {
async.each(users, (user, ecb) => {
Course.findOne({fullName: user.course})
.exec((err, course) => {
if (!err) {
users[users.indexOf(user)].courseId = course._id;
ecb();
} else {
ecb(err);
}
});
}, (err) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
// This part of the code belongs at the route scope
async.waterfall([
getUsers,
findCourse,
findProject
], (err, result) => {
if (!err) {
res.send(result);
} else {
return res.send(err);
}
});
Hope this gives better insight on how you could go about with multiple IO transactions on the same request.

Post data to mongodb

Hi i have end point to post data to mongodb , when i submit a form only ID is submitted I think because am using insert instead of save ,
Here is how it looks:
app.post('/comments', (req, res) => {
const { errors, isVal } = validate(req.body);
if (isVal){
const { author, description } = req.body;
db.collection('comments').insert({ author, description }, (error, result) => {
if (error) {
res.status(500).json({ errors: { global: "Oops something is right!" }});
} else {
res.json({ comments: result.ops[0] });
}
})
} else {
res.status(400).json({ errors });
}
});
The method above is the one saves only ID, other data saved null: I tried to change like this, replacing insert with save some one suggested something like this.
app.post('/comments', (req, res) => {
const { errors, isVal } = validate(req.body);
if (isVal){
const { author, description } = req.body;
db.collection('comments').save({ author, description }, (error, result) => {
if (error) {
res.status(500).json({ errors: { global: "Oops something is right!" }});
} else {
res.json({ comments: result.ops[0] });
}
})
} else {
res.status(400).json({ errors });
}
});
Still the same : here is the result saved in database:
{
"_id": {
"$oid": "5b281457f5b629565c09ce26"
},
"author": null,
"description": null
}
how can I change my method so that it can use save instead of insert?
and what is the different between save and insert in mongodb?
Try with this
let newcollection = db.collection('comments');
newcollection.insert({})

Using async.js for deep populating sails.js

I have a big issue with my function in sails.js (v12). I'm trying to get all userDetail using async (v2.3) for deep populating my user info:
UserController.js:
userDetail: function (req, res) {
var currentUserID = authToken.getUserIDFromToken(req);
async.auto({
//Find the User
user: function (cb) {
User
.findOne({ id: req.params.id })
.populate('userFollowing')
.populate('userFollower')
.populate('trips', { sort: 'createdAt DESC' })
.exec(function (err, foundedUser) {
if (err) {
return res.negotiate(err);
}
if (!foundedUser) {
return res.badRequest();
}
// console.log('foundedUser :', foundedUser);
cb(null, foundedUser);
});
},
//Find me
me: function (cb) {
User
.findOne({ id: currentUserID })
.populate('myLikedTrips')
.populate('userFollowing')
.exec(function (err, user) {
var likedTripIDs = _.pluck(user.myLikedTrips, 'id');
var followingUserIDs = _.pluck(user.userFollowing, 'id');
cb(null, { likedTripIDs, followingUserIDs });
});
},
populatedTrip: ['user', function (results, cb) {
Trip.find({ id: _.pluck(results.user.trips, 'id') })
.populate('comments')
.populate('likes')
.exec(function (err, tripsResults) {
if (err) {
return res.negotiate(err);
}
if (!tripsResults) {
return res.badRequest();
}
cb(null, _.indexBy(tripsResults, 'id'));
});
}],
isLiked: ['populatedTrip', 'me', 'user', function (results, cb) {
var me = results.me;
async.map(results.user.trips, function (trip, callback) {
trip = results.populatedTrip[trip.id];
if (_.contains(me.likedTripIDs, trip.id)) {
trip.hasLiked = true;
} else {
trip.hasLiked = false;
}
callback(null, trip);
}, function (err, isLikedTrip) {
if (err) {
return res.negotiate(err);
}
cb(null, isLikedTrip);
});
}]
},
function finish(err, data) {
if (err) {
console.log('err = ', err);
return res.serverError(err);
}
var userFinal = data.user;
//userFinal.trips = data.isLiked;
userFinal.trips = "test";
return res.json(userFinal);
}
);
},
I tried almost everthing to get this fix but nothing is working...
I am able to get my array of trips(data.isLiked) but I couldn't get my userFInal trips.
I try to set string value on the userFinal.trips:
JSON response
{
"trips": [], // <-- my pb is here !!
"userFollower": [
{
"user": "5777fce1eeef472a1d69bafb",
"follower": "57e44a8997974abc646b29ca",
"id": "57efa5cf605b94666aca0f11"
}
],
"userFollowing": [
{
"user": "57e44a8997974abc646b29ca",
"follower": "5777fce1eeef472a1d69bafb",
"id": "5882099b9c0c9543706d74f6"
}
],
"email": "test2#test.com",
"userName": "dany",
"isPrivate": false,
"bio": "Hello",
"id": "5777fce1eeef472a1d69bafb"
}
Question
How should I do to get my array of trips (isLiked) paste to my user trips array?
Why my results is not what I'm expecting to have?
Thank you for your answers.
Use .toJSON() before overwriting any association in model.
Otherwise default toJSON implementation overrides any changes made to model associated data.
var userFinal = data.user.toJSON(); // Use of toJSON
userFinal.trips = data.isLiked;
return res.json(userFinal);
On another note, use JS .map or _.map in place of async.map as there is not asynchronous operation in inside function. Otherwise you may face RangeError: Maximum call stack size exceeded issue.
Also, it might be better to return any response from final callback only. (Remove res.negotiate, res.badRequest from async.auto's first argument). It allows to make response method terminal

How to get the id of the json data inserted in the Mongo db collection with node js app on Bluemix

I had one json data,I want to pass that JSON data in to Mongo db collection.
The json data is,
json=
{
"customerdetails" : {
"organId" : "sample",
"address" : {
"addressLine1" : "123213",
"postcode" : "RG16QX"
},
"customerName" : "don",
"dob" : "sample"
},
"transactiondetails" : {
"bankDetails" : {
"accountName" : "john",
"bankAddress" : "sample"
},
"brokerId" : "12345"
}
}
I want only customerdetails details json part to be stored in one collection.Then I want to get the id of the inserted json(_id":"nFNBY4GN6m6jjpNEY")..Then I want to replace this id in the customer details value and insert this json in another collection.
{
"customerdetails" :{ "_id":"nFNBY4GN6m6jjpNEY"},
"transactiondetails" : {
"bankDetails" : {
"accountName" : "john",
"bankAddress" : "sample"
},
"brokerId" : "12345"
}
}
The code which I am using is
var jsondata=JSON.parse(json);
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
mongourl="*******";
MongoClient.connect(mongourl, function (err, db) {
console.log("inside mongo client");
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
var collection = db.collection('customerdetails');
collection.insert(jsondata.customerDetails, {safe:true},function (err, result) {
if (err) {
console.log("got error");
console.log(err);
} else {
var collectionid=result._id;
console.log("*********"+collectionid);
console.log("collection"+collection);
console.log('Inserted documents ");
}
});
}
But I am unable to insert in to collection..
And also if it gets inserted how can i get the _id of the inserted data from the collection and replace that with the key value and pass the remaining JSON in to another collection..
Can someone suggest any ideas.
By the way Iam using nodeapp and mongodb service on bluemix.
Thanks
There are 2 issue in your code, we know that javascript is case sensitive and you are using jsondata.customerDetails while you should use json.customerdetails and you must know about insert callback function's argument.
You do not need to use JSON.parse(json); because your your variable json is already object. Here is code
var json = {
"customerdetails" : {
"organId" : "sample",
"address" : {
"addressLine1" : "123213",
"postcode" : "RG16QX"
},
"customerName" : "don",
"dob" : "sample"
},
"transactiondetails" : {
"bankDetails" : {
"accountName" : "john",
"bankAddress" : "sample"
},
"brokerId" : "12345"
}
}
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var mongourl = 'mongodb://localhost:27017/stackoverflow';
MongoClient.connect(mongourl, function (err, db) {
console.log("inside mongo client");
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
var collection = db.collection('customerdetails');
collection.insert(json.customerdetails, {safe:true},function (err, result) {
if (err) {
console.log("got error");
console.log(err);
} else {
json.customerdetails = {
"_id": result.insertedIds[0]
}
console.log("********* Here is updated josn ***************");
console.log(json)
console.log('Inserted documents ');
}
});
}
});

Mongoose - remove array element in update

I have a JSON in this format:
{
_id:5522ff94a1863450179abd33,
userName:'bill',
__v:3,
friends:[
{
_id:55156119ec0b97ec217d8197,
firstName:'John',
lastName:'Doe',
username:'johnDoe'
},
{
_id:5515ce05207842d412c07e03,
lastName:'Adam',
firstName:'Foo',
username:'adamFoo'
}
]
}
And I would like to remove whole corresponding subarray. For example I want to remove user John Doe with ID 55156119ec0b97ec217d8197 so the result will be:
{
_id:5522ff94a1863450179abd33,
userName:'bill',
__v:3,
friends:[
{
_id:5515ce05207842d412c07e03,
lastName:'Adam',
firstName:'Foo',
username:'adamFoo'
}
]
}
So far I have this:
exports.delete = function (req, res) {
var friends = req.friends[0];
friends.update(
{'_id': req.body.friendsId},
{$pull: {'friends.friends': {_id: req.body.friendId}}}, function (err) {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(friends);
}
});
};
But without result and also I'm not getting any error, it will stay just same as before. req.body.friendsId is ID of main array and req.body.friendId is ID of specific user which I want to pull.
Change your update query to this:
exports.delete = function (req, res) {
var friends = req.friends[0]; // assuming the friends object is your mongodb collection
friends.update(
{ '_id': req.body.friendsId },
{ $pull: {'friends': { _id: req.body.friendId } } }, function (err) {
if (err) {
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
res.json(friends);
}
});
};
This will search for documents which have the friends array element _id value = req.body.friendsId and removes the specific array element from that array using the $pull operator.

Categories

Resources