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

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/

Related

unable to store base 64 image in mongodb

I have a requirement to store base 64 image data captured using webcam js in mongodb
I tried to store the image data in mongodb but unable to do so
Server
schema:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ProfilesSchema = new Schema({
name: String,
otherFiles: [Object]
});
module.exports = mongoose.model('Profiles', ProfilesSchema);
express js :
exports.otherFiles = function(req, res) {
console.log("b4" + req.body.key.imgDataField);
var base64Image = new Buffer(req.body.key.imgDataField, 'binary').toString('base64');
req.body.key.imgDataField = base64Image;
console.log("after" + req.body.key.imgDataField);
Profiles.update({
"_id": req.params.id
}, {
$push: {
"otherFiles": {
imgDataField: req.body.key.imgDataField
}
}
}, function(error, profiles) {
if (error) {
}
return res.status(200).json(fnStruncturedData(profiles));
});
};
Client
controller:
$scope.take_snapshot = function() {
debugger;
Webcam.snap(function(data_uri) {
$scope.data = data_uri;
$scope.oData = {};
$scope.oData.imgDataField = data_uri;
getCandidateInterviewListService.fnSavefiles(localStorage.getItem('candidateID'), $scope.oData).then(function(response) {});
document.getElementById('my_result').innerHTML = '<img src="' + data_uri + '"/>';
//console.log($scope.data);
});
$scope.set = true;
}
service:
this.fnSavefiles = function(id, sData) {
debugger;
return ajaxServiceManager.fnQuery({
sUrl: 'http://192.168.208.31:4000/onboardvue/profiles/otherFiles/' + id,
sMethod: "PUT",
oData: {
key: sData
}
});
};
Please help me with this
I am using mongodb ,express js
I store a base 64 image like this:
MyController.js
exports.addBook = function (req, res) {
'use strict';
var book = new Book({
title : req.body.title,
author : req.body.author,
category : req.body.category,
synopsis : req.body.synopsis,
units : req.body.units,
avatar: {
data : base64Image('your path' + req.body.avatar + '.jpg'),
contentType: 'image/png'
}
});
function base64Image(src) {
return fs.readFileSync(src).toString("base64");
}
book.save(function (err, books) {
if (err) {
return res.status(500).send(err.message);
}
res.status(200).jsonp(books);
});
};
Hope it helps you

How to insert array to mongodb using node.js

I have an array like [ 570dec75cf30bf4c09679deb, 56fe44836ce2226431f5388f ]. Now I want insert this for new collection named notifications like
{
"_id": ObjectId("57bd39c9734ff3602a312b33"),
"userId": ObjectId("570dec75cf30bf4c09679deb")
}
and
{
"_id": ObjectId("57bd39c8734ff3602a312b32"),
"userId": ObjectId("56fe44836ce2226431f5388f ")
}
I have written a query in node.js to insert this but it inserting last element of array two times like this
{
"_id": ObjectId("57bd39c9734ff3602a312b33"),
"userId": ObjectId("56fe44836ce2226431f5388f ")
}
and
{
"_id": ObjectId("57bd39c8734ff3602a312b32"),
"userId": ObjectId("56fe44836ce2226431f5388f ")
}
The query I have written like this
app.js
router.post('/creatList', function(req,res){
console.log(req.body.email);
var emails = req.body.email;
if(req.body.wData.wishListType == 'Shared'){
var findUsers = function(db, callback) {
var cursor;
cursor = db.collection('users').find({email: { $in: emails }})
cursor.toArray(function(err, docs){
if(err){
callback(new Error("Some problem"));
} else {
callback(null,docs);
}
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
findUsers(db, function(err,docs) {
db.close();
console.log(docs);
for(var key in docs){
console.log(key);
var ids = docs[key]._id;
console.log(ids);
var insertDocument = function(db, callback) {
db.collection('notifications').insert({
"userId" : ids,
},function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the notifications collection.");
callback();
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
}
});
});
});
You basically need to remap your results from you users.find() so that they will match your schema for your notifications collection. This should work:
var docsToInsert = docs.map(function (doc) {
// this assumes your users collection has an _id that you actually want to use as the reference for you notifications.userId field
// actually, you probably want "return {"userId": ObjectID(doc._id)};" since you are using the native mongodb api
return { "userId": doc._id };
});
So, simplifying what you have for the rest a bit, it would be:
router.post('/creatList', function (req, res) {
console.log(req.body.email);
var emails = req.body.email;
if (req.body.wData.wishListType == 'Shared') {
var findUsers = function (db, callback) {
var cursor;
cursor = db.collection('users').find({ email: { $in: emails } });
cursor.toArray(function (err, docs) {
if (err) {
callback(new Error("Some problem"));
} else {
callback(null, docs);
}
});
};
MongoClient.connect(config.database, function (err, db) {
assert.equal(null, err);
findUsers(db, function (err, docs) {
db.close();
console.log(docs);
var docsToInsert = docs.map(function (doc) {
// this assumes your users collection has an _id that you actually want to use as the reference for you notifications.userId field
// actually, you probably want "return {"userId": ObjectID(doc._id)};" since you are using the native mongodb api
return { "userId": doc._id };
});
MongoClient.connect(config.database, function (err, db) {
assert.equal(null, err);
db.collection("notifications").insert(docsToInsert, function (err, result) {
if (err) {
// handle the err however you like
throw err;
}
db.close();
});
});
});
});
}
});

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

Angular Put Method

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

Resources