How to update array of documents in mongodb? - arrays

I have AdminGroupOperation model which looks like this:
var AdminGroupOperation = new mongoose.Schema({
module : String,
adminGroup: {type: mongoose.Schema.Types.ObjectId, ref: 'AdminGroup'},
operations: [{type: mongoose.Schema.Types.ObjectId, ref: 'Operation'}],
recycled: Number
});
and my Operation model which looks like this:
var Operation = new mongoose.Schema({
name : String,
value: Boolean,
recycled: Number
});
How can I update operations array in AdminGroupOperations model? In my api I have something like this but this wont work..
exports.update = function (req, res, next) {
var data = req.body;
AdminGroupOperation.findByIdAndUpdate({"_id": req.params.id}, {
module : data.module,
adminGroup: data.adminGroup._id,
operations: data.$.operations_id
},
{new: true},
function (err, secoperation) {
if (err) {
return next(err);
}
secoperation.save(function (err) {
if (err) {
return next(err);
}
});
res.json({'status': 'updated', 'ID': req.params.id});
})
};

you have to use id without request, I mean :
AdminGroupOperation.findByIdAndUpdate req.params.id, { $set:{
module : data.module,
adminGroup: data.adminGroup._id,
operations: data.$.operations_id
}}, {new: true},
function (err, secoperation) {
if (err) {
return next(err);
}
secoperation.save(function (err) {
if (err) {
return next(err);
}
});
res.json({'status': 'updated', 'ID': req.params.id});
})
};
I am not sure for the option : {new : true}, or you can simply use update with using the request to find with the ID

Related

PayPal Adaptive producing error Response ack is Failur

app.post('/api/pay_for_palns_credit_card', function(req, res) {
console.log(req.body);
db = req.db;
var email = 'admin#qhop.com';
var amount = req.body.amount;
var firstname = req.body.firstname;
var lastname = req.body.lastname;
var cardtype = req.body.cardtype;
var cardnumber = req.body.cardnumber;
var expiremonth = req.body.expiremonth;
var expireyear = req.body.expireyear;
var cvv = req.body.cvv;
var payer = req.body.email;
var collection = db.get('paymentscollections');
var Paypal = require('paypal-adaptive');
var paypalSdk = new Paypal({
userId: 'id',
password: 'password',
signature: 'signatures',
sandbox: true //defaults to false
});
var payload = {
requestEnvelope: {
errorLanguage: 'en_US'
},
actionType: 'PAY',
currencyCode: 'USD',
feesPayer: payer,
memo: 'this is a test',
cancelUrl: 'http://test.com/cancel',
returnUrl: 'http://test.com/success',
receiverList: {
receiver: [{
email: email,
amount: amount,
primary: 'false'
}]
}
};
paypalSdk.pay(payload, function(err, response) {
console.log(payload);
if (err) {
console.log('in here');
console.log(err);
res.send(err);
} else {
collection.insert({
payload
}, function(err, doc) {
if (err) {
console.log(err);
// If it failed, return error
res.send(err);
} else {
console.log(doc);
res.send(doc);
}
});
}
});
});
I am getting the following error while using paypaladaptive.
These are all the details I have of error.
Error: Response ack is Failure. Check the response for more info.
at IncomingMessage. (D:\Qhoppaypal1\node_modules\paypal-adaptive\

How to query mongodb on a specific field

I have a collection of objects with the following schema :
var Meetup = new Schema({
name: String,
text:String,
});
I would like to get all of the meetups whom name contain a string.
Here is my api :
module.exports.list = function (req, res) {
Meetup.find({}, function (err, results) {
res.json(results);
});
}
and in my angular controller i have :
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
can anyone help
Query on specific field
ModelName.find({fieldName: value}, function (err, results) {
//...
});
so for your case query will be like:
exports.list = function (req, res) {
Meetup.find({name: req.query.name}, function (err, results) {
res.json(results);
});
};
and angular controller like
var Meetup = $resource('/api/meetups', {}, {
query: {method: 'get', isArray: true}
});
$scope.meetups = []
Meetup.query({name: 'yourName'}).$promise.then(function(results) {
// console.log(results);
$scope.meetups = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});

URL is not hitting the server(mongodb)

i want to get the object from my collection based on the quesListName which i send as a param to the server
here is my service
angular.module('hrPortalApp')
.service('getCandidateInterviewListService', function($http, ajaxServiceManager) {
var sUrlQuestions = "http://localhost:4000/onboardvue/questions/qListQuestions/";
return {
fnGetQuestions: function(qListName) {
return ajaxServiceManager.fnQuery({
sUrl: sUrlQuestions,
sMethod: "GET",
oData: null,
oParams: {
quesListName: qListName
}
});
},
};
});
below is my schema
var QuestionsSchema = new Schema({
topicName: String,
quesListName: String,
question:String
});
and the query which i wrote to get the object based on quesListName is
exports.query = function(req, res) {
Questions.find({quesListName:req.query.quesListName}, function(err, questions) {
if (err) {
return handleError(res, err);
}
return res.status(200).json(fnData(questions));
});
};
but i am getting 500 error

how to post http req with multiple param in angularjs,mongoose

In the view html page there is a form with a table and when i submit the form two objects are created cvm and schedules for form and table. i somehow want schedules(which is an array) to be related to cvm form. so i tried this way...
Here is the defined model
$scope.addSchedule=function(schedule)
{
console.log(schedule.startDate);
console.log(schedule.location);
$scope.schedules.push({
startDate: schedule.startDate,
location: schedule.location
});
schedule.startDate='';
schedule.location='';
};
var inData={'cvm': $scope.cvm,'schedules': $scope.schedules};
$scope.addCvm=function()
{
console.log($scope.cvm);
console.log($scope.schedules);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
sever side Connection
i guess somthing i missed in this part
/* POST */
router.post('/', function(req, res, next)
{
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
Here is my schema for mongodb
'use strict';
var mongoose = require('mongoose');
var cvmSchema = new mongoose.Schema({
visitOrganization: { type: String },
visitAgenda: { type: String },
accountManager: { type: String },
visitCoordinator: { type: String },
schedules:[{
startDate: String,
location: String
}]
});
module.exports = mongoose.model('visit', cvmSchema);
plz help !! thanks in advance
I think you should try with below change :
//Change addCvm function
$scope.addCvm = function(){
var inData = $scope.cvm;
inData.schedules = $scope.schedules;
console.log(inData);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
// Server Side API Code
router.post('/cvmApi', function(req, res, next) {
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
The thing is i dint realize my variable startDate was not in type string in my html page as i was using some date plugins....
soo ya thats it worked brilliantly ...
addCvm function in controller thanks to rana ;-)
$scope.schedules=[];
$scope.addCvm = function(){
var inData = $scope.cvm;
inData.schedules = $scope.schedules;
console.log(inData);
$http.post('/cvmApi',inData).success(function(response) {
console.log(response);
refresh();
});
};
server side Api
router.post('/', function(req, res, next) {
console.log("Cvm api post '/'");
console.log("retrieving:: " + req.body);
cvmModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
may be not required but i changed my schema though....
var cvmSchema = new mongoose.Schema({
visitOrganization: { type: String },
visitAgenda: { type: String },
accountManager: { type: String },
visitCoordinator: { type: String },
schedules: [{
dateStart: { type:String },
locationHere: { type: String }
}]
});

Populating an object with an array of objects that have it's _id

I have a bunch of tasks that when I create/edit I would like to be able to assign to a project. The way I have thought this should be done is the save the project ID to the task and the some how from the project collection reach into the task collection search for all objects with the matching project _id and then populate the tasks array with the correct tasks.
Now I don't know if this is the correct way and as you can see from my code I think I am half way there but I am not sure exactly how to populate a project with the correct tasks. I am using mongoose and it would be great if someone could let me know what I am doing wrong and how I could do it better.
I have a list of tasks that I want to link to projects.
TaskSchema:
var TaskSchema = new Schema({
title: { type: String},
description: String,
project: [{ type: Schema.Types.ObjectId, ref: 'Project'}]
});
Tast Controller:
'use strict';
var _ = require('lodash');
var Task = require('./task.model');
// Get list of tasks
exports.index = function (req, res) {
var populateUsers = {path:'users', select:'name profileImage email'};
Task
.find({})
.populate(populateUsers)
.populate('projects')
.exec(function (err, tasks) {
if (err) { //handle error
return handleError(res, err);
}
return res.json(200, tasks);
});
};
exports.show = function (req, res) {
var populateUsers = {path:'users', select:'name profileImage email'};
Task
.findById(req.params.id, function (err, task) { //get task
if (err) { //handle error
return handleError(res, err);
}
return task;
})
.populate(populateUsers)
.exec(function (err, task) { //use a callback to handle error or return tasks if everything is ok
if (err) { //handle error
return handleError(res, err);
}
return res.json(task); //return task filled with "users"
});
};
// Creates a new task in the DB.Î
exports.create = function(req, res) {
Task.create(req.body, function(err, task) {
if(err) { return handleError(res, err); }
return res.json(201, task);
});
};
// Updates an existing task in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Task.findById(req.params.id, function (err, task) {
if (err) { return handleError(res, err); }
if(!task) { return res.send(404); }
var updated = _.merge(task, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, task);
});
});
};
// Deletes a task from the DB.
exports.destroy = function(req, res) {
Task.findById(req.params.id, function (err, task) {
if(err) { return handleError(res, err); }
if(!task) { return res.send(404); }
task.remove(function(err) {
if(err) { return handleError(res, err); }
return res.send(204);
});
});
};
function handleError(res, err) {
return res.send(500, err);
}
ProjectSchema:
var ProjectSchema = new Schema({
name: String,
dateCreated : {
type : Date,
default : Date.now
},
tasks: [{ type: Schema.Types.ObjectId, ref: 'Task'}]
});
Get Project List
// Get list of projects
exports.index = function (req, res) {
Project
.find({})
.populate('tasks')
.exec(function (err, projects) {
if (err) { //handle error
return handleError(res, err);
}
return res.json(200, projects);
});
};

Resources