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 = [];
});
Related
Trying to send a request from my factory to the back end, getting the following error: POST http://localhost:8000/messages/58d4b22d57f49028608f7bf9 400 (Bad Request)
Factory:
app.factory('usersFactory', function ($http) {
var factory = {};
var current_user = [];
factory.login = function (data, callback) {
$http.post('/users/', data)
.then(function (response) {
current_user.push(response.data);
callback(current_user);
})
};
factory.getUser = function (callback) {
callback(current_user);
}
factory.destroy = function (callback) {
current_user = [];
callback();
}
factory.writePost = function (data) {
console.log(data);
console.log(current_user[0]._id)
$http.post('/messages/' + current_user[0]._id, data)
.then(function (response) {
$location.url('/wall');
})
}
return factory;
});
Server routes:
var wall = require('./../controllers/serverController.js')
module.exports = function(app){
app.post('/users/', function (request, response) {
wall.login(request, response);
});
app.post('/messsage/:id', function (request, response) {
wall.writeMessage(request, response);
})
}
Sever controller:
module.exports =
{
writeMessage: function (request, response) {
User.findOne({ _id: request.params.id }, function (err, user) {
var message = new Message({ message: request.body, _user: request.params.id });
message.save(function (err) {
user.messages.push(message);
user.save(function (err) {
if (err) {
response.json(err);
}
})
})
})
}
}
this is error of sever side not angular, try to check logs of server.
Also you are using Message , do have schema imported in that ?
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
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 }
}]
});
Here how my button's set up. The Updates.getUpdates is working. Updates.postAnUpdate returns 404
$scope.postUpdate = function () {
console.log($scope.update);
Updates.postAnUpdate($scope.update);
Updates.getUpdates().then(function (data) {
$scope.updates = data;
});
};
Here is my lovely services
app.factory('Updates', ['$http',
function ($http) {
return {
//Get the current users messages
getUpdates: function () {
return $http({
url: '/updates/',
method: 'get'
}).then(function (result) {
return result.data;
});
},
postAnUpdate: function (update) {
return $http({
url: '/updates/post',
method: 'post',
data: {
update:update,
}
}).then(function (result) {
return result.data;
});
}
};
}]);
Here's my routes to handle the urls
var updates = require('./routes/updates.js');
//Project Updates
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
And finally, here's the code that works with a 200 and console text.
exports.getAll = function (req, res) {
console.log('It worked');
}
So everything should be working for the post too, but it isn't. I'm just trying to do a console command so I know it works and I'm getting a 404
exports.newPost = function (req, res) {
var db = mongo.db,
BSON = mongo.BSON,
newPost = {};
console.log('This is giving me 404 instead of showing up in terminal');
newPost.content = req.body.update;
newPost.author = req.user._id;
newPost.date = new Date();
db.collection('updates').save(newPost, function (err, result) {
if (err) {
throw err;
}
console.log(result);
});
}
Looks as though this is a simple typographic error. in your routes:
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
I think you want
app.post('/updates/post', updates.newPost);
Total newbee here. Given this service.js how can I go about returning terms data from sql server
app.service('termsService', function () {
this.getTerms = function () {
return terms
};
var terms = [
{
termid: 11, term: 'Shanika', termDefinition: 'Passmore'
}
];
});
The code below works well on its own so I want to return terms data in the service call above
var sql = require('msnodesql')
, nconf = require('nconf')
,express = require('express');
nconf.env()
.file({ file: 'config.json' });
var connectionString = nconf.get("SQL_CONN");
var app = express();
app.configure(function () {
app.use(express.bodyParser());
});
app.get("/", function(req, res) {
sql.open(connectionString, function(err, conn) {
if(err) {
}
else {
conn.queryRaw("SELECT TOP 10 termid, term, termDefinition FROM Terms", function(err, results) {
if(err) {
}
else {
res.json(results);
}
});
}
});
});
app.listen(3000);
A code for your angular service :
function Service($http) {
var Service = {};
Service.getCriteria = function (criteria,callback) {
$http({
url: "YOUR URL",
params: criteria,
method: "GET",
isArray: true
}).success(callback)
}
return Service;
}
Be aware of that is an async call, so use promises, callback or sync methods.