URL is not hitting the server(mongodb) - angularjs

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

Related

Validation on POST request

I am using angular and talking to an express backend. I can retrieve data from my .get, but my .post is generating a validation error
Client-controller:
$scope.addFriend = function()
{
friendsFactory.addFriend($scope.newFriend, function (data)
{
$location.url('/friends' + data._id);
});
}
Client-factory:
factory.addFriend = function (newFriendData, callback) {
$http.post('/friends', newFriendData)
.then(function(response)
{
console.log(response.data);
//callback(response.data);
})
}
Server-route:
app.post('/friends', function (request, response) {
console.log('routes')
friends.create(request, response);
})
Server-controller:
create: function(request, response)
{
console.log('request');
var friendInstance = new Friend();
friendInstance.first_name = request.params.fname;
friendInstance.last_name = request.params.lname;
friendInstance.b_day = request.params.bday;
friendInstance.save(function(err,data)
{
if (err)
{
response.json(err);
}
else {
rewponse.json(data);
}
})
Error on console:
Object {errors: Object, message: "Friend validation failed", name: "ValidationError"}
this is most likely a mongoose error, the document that you're trying to persist does not follow the Friend schema.

I want to write data to mongodb Database using node.js

Right now i am writing data to json file and getting that back to html page to display. Now i want to do same with mongodb Database. I have tried something but, it doesn't working.
app.get('/', function(req, res){
url = 'http://www.amazon.in/Sony-Xperia-Z3-Copper-32GB/dp/B010V448ZC/ref=pd_rhf_se_s_cp_6?ie=UTF8&dpID=419rmomR%2BjL&dpSrc=sims&preST=_SL500_SR135%2C135_&refRID=19RT23W7T48Z99XNT6GK';
request(url, function(error, response, html){
if (!error) {
var $ = cheerio.load(html)
var json = {Product_Name : "", Brand : "", Color : "", Image : "", Price : "", Rating : ""};
var P_name = $('#title').children().text();
var brand = $('#brand').text();
var color = $('.a-row').find('span.selection').text();
var price = $('#price').find('span.a-size-medium').text();
var rating = $('#averageCustomerReviews').find('span.a-icon-alt').text();
var image = $('.imgTagWrapper').children().attr('src');
/*json.Product_Name = P_name;
json.Brand = brand.trim();
json.Color = color.trim();
json.Price = price.trim();
json.Rating = rating.trim();
json.Image = image.trim();
fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){
console.log('File successfully written! - Check your project directory for the output.json file');
})*/
var insertDocument = function(db, callback) {
db.collection('proInfo').insertOne( {
"Product_Name": P_name,
"Brand":brand,
"Color":color,
"Price":price,
"Rating":rating,
"Image":image
}, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the proInfo collection.");
callback(result);
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
res.send('Check your console!')
} else {
console.log("We’ve encountered an error: " + error);
}
})
})
It shows some error in console.log
D:\Hemanth\Node Js\web scraper\node_modules\mongodb\lib\url_parser.js:20
throw new Error('invalid schema, expected mongodb');
^
Error: invalid schema, expected mongodb
at module.exports
Can anybody help me to fix this issue?
Use module export in your node js routes and define the method inside the module.export as mentioned below :
module.export {}
and then call the method, apply routes in the server.js under node application :
erc(app,
{
controllers: __dirname + '/routes',
routes:{'/methodnametobecalled': { action: 'routesfilename#methodname'}
}
});
Initialize Mongoose and Schema
var mongoose = require('mongoose');
mongoose.connect('mongodb://YOURVALUES.mongolab.com:11111/NAME');
var schema = new mongoose.Schema({ name: 'string', account: 'string', date: 'string' });
var accountz = mongoose.model('accountz', schema);
Create
var small = new accountz({
name: "SAMZ",
account: "Monthly",
date: "29/12/2015"
});
small.save(function (err) {
if (err){
console.log("Error in Save");
}else{
console.log("Save Sucessfully");
}
});
Read
accountz.find().exec(function(err, data){
if (err){
console.log("Error in Reading");
}else{
console.log("The value = " + data);
}
});
Update
accountz.findOne({ "_id": "0023"}, function (err, doc){
doc.name = editObj.name;
doc.account = editObj.account;
doc.date = editObj.date;
doc.save(function (err) {
if (err){
console.log("Error in Updating");
}else{
console.log("Updated Sucessfully");
}
});
});
Delete
accountz.remove({ "_id": "0023"}).exec(function(err, data){
if (err){
console.log("Error in Deleting");
}else{
console.log("Deleting Sucessfully");
}
});
Ref This link https://shiyamexperience.wordpress.com/2015/12/29/mongodb-crud-using-mongoose/

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

Find and save loop (MongoDB Node Express)

I have this controller which fetch data from instagram api.
controller.prototype.getData = function getData(url, tag, callback) {
var clientId = '81e3d3f35c8a4438964001decaa5a31f'
var catchAll = [];
var config = {
'params': {
'client_id': clientId,
'callback': 'JSON_CALLBACK'
}
}
vm.url = 'https://api.instagram.com/v1/tags/' + tag + '/media/recent/';
http.jsonp(url, config)
.then(function(response) {
vm.imageData = vm.imageData.concat(response.data.data);
vm.instagram.storeData(vm.imageData).then(function(response) {
})
var paging = response.data.pagination;
if (paging.hasOwnProperty('next_url')) {
getData(paging.next_url)
} else {
callback.call();
}
})
}
then on node mongodb controller i have this
exports.create = function(req, res) {
var dataObj = req.body;
dataObj.forEach(function(item) {
Data.find({
'id': item.id
}, function(err, data) {
if (err) {
return handleError(res, err);
}
if (data.length == 0) {
Data.create(item, function(err, data) {
if (err) {
return handleError(res, err);
}
});
}
});
});
};
The logic here is that if user is not existing in the collection i will save it. my question is why is it that it takes too long to response if have lets say 300 instagram object ? is there a ways how to do this in optimal performance?

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