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 }
}]
});
Related
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 = [];
});
I've having issues with both my routes and getting/saving the data with mongodb. It seems to have validation errors when saving or maybe not posting JSON. Any ideas?
Here's my mongoose schema:
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var sitesEntrySchema = new Schema({
ip: {
type: String,
required: true,
trim: true
},
domain: {
type: String,
required: true,
trim: true
},
wp: {
type: String,
required: true,
trim: true
},
host_name: {
type: String,
required: true
},
hosted: {
type: Number,
required: true
}
});
// make this available to our users in our Node applications
var Site = mongoose.model('Site', sitesEntrySchema);
module.exports = Site;
And my angular http request
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('/api/mongo')
.then(function(response) {
console.log(response.data);
$scope.myData = response.data;
});
});
app.controller('FormCtrl', function($scope, $http) {
$scope.formData = {};
$scope.addSite = function() {
$http.post('/api/create', $scope.formData)
.success(function(data) {
console.log($scope.formData);
$scope.formData = {}; // clear the form so our user is ready to enter another
swal(
'Good job!',
'Site was added!',
'success'
);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
});
My express routes:
var express = require('express');
var router = express.Router();
var Site = require('../models/site');
//Return From Mongo
router.get('/api/mongo', function(req, res) {
Site.find({}, function(err, sites) {
if (err)
res.send(err)
res.send(sites);
});
//res.json({"yo": "yo this shit works"});
});
//Add A Site
router.post('/api/create', function(req, res, next) {
//create object with form input
var siteData = {
ip: req.body.ip,
domain: req.body.domain,
wp: req.body.wp,
host_name: req.body.host_name,
hosted: req.body.hosted
};
// use schema's 'create' method to insert doc into mongo
Site.create(siteData, function(error) {
if (error) {
//return next(error);
res.send(error);
} else {
return res.json({ message: 'Site added!' });
}
});
});
Without specific outputs that show what is going wrong, here are a few things stick out to me. The first is not always responding with json. You should also try using next() to handle your errors since Express will make sure to send back a correct error response. With these changes, your get route looks like:
//Return From Mongo
router.get('/api/mongo', function(req, res, next) {
Site.find({}, function(err, sites) {
if (err) {
next(err)
} else {
return res.json(sites);
}
});
});
Secondly, It is best practice to return the newly created resource, so your create route should look like
//Add A Site
router.post('/api/create', function(req, res, next) {
//create object with form input
var siteData = {
ip: req.body.ip,
domain: req.body.domain,
wp: req.body.wp,
host_name: req.body.host_name,
hosted: req.body.hosted
};
// use schema's 'create' method to insert doc into mongo
Site.create(siteData, function(error, site) {
if (error) {
next(error);
} else {
return res.json(site);
}
});
});
In addition, depending on your version of Angular, you might be using the deprecated promise syntax for the post request. You should be using .then(), not .success() and .error(). This might also be causing an issue.
Lastly, you should try your best to follow REST guidelines for your routes and responses. It will make it much easier to extend your web app and will keep you more organized. Here is a good Express/Node resource for that https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4.
ADDED: Here is an example of how you can log your errors depending on production/development environments
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
console.log('err:', err.status, err.message);
res.status(err.status || 500);
res.json({message: err.messages});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
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
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
I'm trying to do an Angular update using $http.put. The data is successfully passes from the form to the client controller when I do console.log, but when I do $http.put request. It comes back as PUT http://localhost:3000/articles 500 (Internal Server Error).
This is the client side articles.controller.js:
$scope.updateArticle = function(){
var data = {
id: $routeParams.id,
title: $scope.article.title,
body: $scope.article.body,
category: $scope.article.category
}
console.log(data);
$http.put('/articles', data).success(function(data, status){
console.log('abc');
});
$location.path('/articles');
}
This is the server side route for articles.js:
router.put('/', function(req, res, next){
var id = req.body.id;
var data = {
title: req.body.title,
category: req.body.category,
body: req.body.body
};
Article.updateArticle(id, data, function(err, article){
if(err){
console.log(err);
}
res.location('/articles');
res.redirect('/articles');
});
});
And this is the model article.js:
module.exports.updateArticle = function(id, data, callback){
var title = data.title;
var body = data.body;
var category = data.category;
var query = {_id: id};
Article.findById(id, function(err, article){
if(!article){
return next(new Error('Could not load article'));
} else {
article.title = title;
article.body = body;
article.category = category;
article.save(callback);
}
})
}
Why don't you try making a router.put route that targets "/articles" directly? Your articles.js file should look like this:
router.put('/articles', function(req, res, next){
console.log("Hit my route!");
//etc...
});