**model schema**
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var item = new Schema({
name:{type: String,
required: true},
price:{type: String}
})
var object=new Schema({
name:{type: String,
required: true},
items: [item]
});
api.js, posting data to server
router.post('/objectss', function(req, res){
var object= new Object(); **
how can i save array of objects in array
**
object.items.push({firstName: req.body.fname, lastName: req.body.lname});
object.name = req.body.name;
object.save(function (err) {
if(err) throw err;
res.json({success: true, message:'allahuakbar'});
});
// saved!
});
angularjs controller
$scope.addProduct = function(){
$scope.items.push({
fname: $scope.item.fname,
lname: $scope.item.lname
});
$scope.item = {};
}
$scope.submitx = function(inv, item){
console.log(inv);
var object = {
name:inv.name,
fname:items.fname,
totalValue: 0
}
PostBlog.createInvoice(objects).then(function(data){
console.log(data);
});
$scope.objects= {};
}
please see this code and help me! struggling over weeks . there is array of object like a["name":carrot, "price":24, "":, etc]
those who get stuck refer to this instead of using method
router.post('/invoices', function(req, res){ //by making route in from
var invoice = new Invoice();
for (var i = 0; i < req.body.length; i++) {
invoice.items.push({name:req.body.fname[i].fname});
}
invoice.name = req.body.name;
//invoice.items.insertMany(items, function(error, next) {
invoice.save(function (err) {
if(err) throw err;
res.json({success: true, message:'allahuakbar'});
});
// saved!
});
Related
factory:
angular.module('clientApp').factory('Di', function($http) {
return {
create: function(dis){
return $http.post('/dis', dis);
}
});
Controller:
'use strict';
angular.module('clientApp').controller('AdminCtrl', function($scope, toastr, Di) {
$scope.di = {};
$scope.dis = [];
$scope.add = function(){
Di.create($scope.di).then(function(response){
console.log(response, 'front data post')
$scope.dis.push(response.data);
$scope.di= {};
});
};
});
When I console.log() the response, the only thing I see in response.data is the hashKey. I do see the object in response.config.data, but from what I've seen online, this is just the original object i'm sending to the database, not the returned promise, right?
The data is saving to the database.
What am I doing wrong? I've done a similar configuration successfully with other promises, but the response is not what I'm expecting here.
API
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DiSchema = new mongoose.Schema({
name: { type: String, lowercase: true , required: true },
photo: { type: String },
email: { type: String, unique: true, lowercase: true },
year: { type: Number},
timestamp: { type : Date, default: Date.now },
description: { type: String},
location: { type: Array },
social: {
website: {type: String},
facebook: {type: String },
twitter: {type: String },
instagram: {type: String }
}
});
DiSchema.methods.create = function(o, cb){
this.model.save(o, cb);
};
module.exports = mongoose.model('Di', DiSchema);
controller:
'use strict';
var Di = require('../models/di');
exports.create = function(req, res){
Di.create(req.body , user, function(err, di){
console.log('req.body.di', req.body);
res.send({di:di});
});
};
Routes:
var dis = require('../contollers/dis');
app.post('/dis', dis.create);
You had a typo with an extra parameter within your create function.
exports.create = function(req, res){
Di.create(req.body , function(err, di){
console.log('req.body.di', req.body);
res.send({di:di});
});
};
I think you should bind your promise to the scope.
Would that fix the problem? Can you try?
$scope.add = function(){
Di.create($scope.di).then(function(response){
console.log(response, 'front data post')
$scope.dis.push(response.data);
$scope.di= {};
}.bind($scope));
};
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/
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 }
}]
});
In controller.js:
angular.module('CRUD').controller('myController',['$scope','$http', function($scope,$http){
$scope.sendData = function(){
console.log($scope.data1);
var formData = {
"username" :$scope.username,
"email" :$scope.email
};
$http({
url:'/formData',
method:'POST',
data:formData
}).success(function(data){
console.log(data);
});
}
}]).directive("myFirstDirective",function(){
return
{
template:"<b>custom directive</b>",
restrict:'E';
}
});
In your nodeJS route API
//User Schema
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
email: {
type: String,
unique: true //means the email has to be unique across all documents
}
});
UserSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err) {
return done(err);
}
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');
module.exports = mongoose.model('User', UserSchema);
...
//API
app.post('/formData', function(req, res){
User.create(req.body, function(err){
if (!err){
res.send(200); //user created
}
else {
if (err.name === 'ValidationError') res.send(409); //stands for form validation error
else res.send(500);
}
});
});
Good practice to put your requests in the service. For example
angular.module('CRUD').controller('myController',['$scope','$http', 'CRUDService', function($scope,$http, CRUDService){
$scope.sendData = function(){
CRUDService.createUser({
username: $scope.username,
email: $scope.email
}).then(function(res){
//all good user was created
}, function(err){
//error, failed to create user
if (err.status === 409){
//email already exists
}
});
}
}]).service('CRUDService', ['$http', function($http){
this.createUser = function(postData){
return $http.post('/formData', postData);
}
}]);
Basically I have a User schema. Within the schema I have the following item which contains the id's of all users. The user follows inside an array.
followers: [{
type: String,
required: false,
unique: false
}],
My question is: how do I get all the results from the followers array only so I can run a ng-repeat with them?
This is what I have tried.
Get Followers controller:
(function(){
angular.module('Scrimbox')
.controller('GetFollowingController'
, ['$scope', '$http', 'User', '$routeParams', '$location'
, function( $scope, $http, User, $routeParams, $location){
$scope.following = function(){
//Empty object to send to server
var request = {};
//get follower id
var FollowerId = $routeParams.id;
//bundle into the object to send to server
var request = {
follower: FollowerId
};
//send to server
$http.post('api/social/getfollowing', request)
.success(function(response){
console.log(response);
$scope.following = response.following;
}).error(function(error){
console.log(error);
});
};
$scope.following();
}]);
}());
getfollowing on the server:
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.getfollowing = function(req, res){
var thefollower = req.body.follower;
User.findOne({ _id: thefollower }).populate('_following').exec(function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
console.log(user);
res.jsonp(user);
}
})
};
Called using:
app.post('/api/social/getfollowing', getfollowingController.getfollowing);
This is the response I get from the server:
But how do I only get all the ids from the following array?
Then how do I use them for a ng-repeat?
ok i did get this thanks for the responses.
i had to query the mongoDB for the user then create a variable for the followee's ID's then run a forEach Loop over all the IDs
var mongoose = require('mongoose'),
User = require('../../models/UserModel'),
async = require('async');
module.exports.getfollowing = function(req, res){
//grab the Users ID from the body
var thefollower = req.body.follower;
//create empty array that i want to populate with the followee's ID and Avatar url
var obj = [];
//query mongo for the user
User.findOne({ _id: thefollower }, function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
//grab the following element of the users mongo schema -- should return all the followee's ID's -- tested works
var following = user.following;
//iritate throught all the followee's
async.forEach(following, function(item, callback) {
//current followee
var user = item;
//query mongo for the followee
User.findOne({_id: user}, function(err, followee, callback){
//get followee's ID and Avatar url
var id = followee._id;
var avatar = followee.avatar;
//add the followee's ID and Avatar url to the obj array
obj.push({
id: id,
avatar: avatar
});
});
//see if this worked - returns empty
console.log(obj);
callback();
}, function(err) {
//see if this worked - returns empty
console.log(obj);
//respond to the client - returns empty
res.json(obj);
});
}
});
};