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
Related
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 }
}]
});
I am creating and sending a UID on the server side to the client side when the user visits a web page. I would like to use that UID as the subfolder to store each project a particular user posts to the server. I'm trying to figure out how best to accomplish this. When I use the code below, I am unable to access the UID in the Projects factory from the UserFactory.
Javascript (Angular):
myApp.factory('UserFactory', function UserFactory($http, API_URL, AuthTokenFactory, $q) {
return $http.get(API_URL + '/api/authenticate').then(function success(response) {
AuthTokenFactory.setToken(response.data.token);
return response;
});
});
myApp.factory('AuthTokenFactory', function AuthTokenFactory($window) {
var store = $window.localStorage;
var key = 'auth-token';
return {
getToken: getToken,
setToken: setToken
};
function getToken() {
return store.getItem(key);
}
function setToken(token) {
if (token) {
store.setItem(key, token);
} else {
store.removeItem(key);
}
}
});
myApp.factory('Projects', function($http, API_URL, UserFactory, AuthTokenFactory) {
var uid = UserFactory.response.data.token
var Projects = {
};
Projects.get = function(id) {
return $http.get(API_URL + '/api/projects/' + uid + id);
};
Projects.create = function(userData) {
return $http.post(API_URL + '/api/projects/' + uid, userData).then(function error(response) {
var data = response.data;
});
};
return Projects;
});
Node
apiRouter.get('/authenticate', function(req, res) {
var uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
var token = jwt.sign({
uid: uid
}, superSecret, {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
message: 'Enjoy your token!',
uid: uid,
token: token
});
});
I am trying to get the data from my form into my hapijs server. I don't seem to be managing. When I submit the form, the data is passed as undefined which trigers an error on the server. From what I understand hapi parses the data automatically.
Could someone please help me understand what I am doing wrong? Why am I getting undefined?
The function that handles the form data is sendworkout.
These are my routes:
var path = require('path');
var _ = require('underscore');
var couchbase = require('couchbase');
//Connect to database.
var db = db || new couchbase.Connection({host: 'localhost:8091', bucket: 'default'}, function(err) {
if (err) {
console.log('Connection Error', err);
} else {
console.log('Connected!');
}
});
console.log(db);
//We have a pending connection to the test database running on localhost.
//We now need to get notified if we connect successfully or if a connection error occurs
var landingPage = {
handler: function(req, reply) {
reply.file('index.html');
}
};
var getWorkouts = {
handler: function (req, reply) {
// set options for databse query
var q ={
descending: true,
stale: false
};
// show multiple exercises - db.view(designDocument, viewName, options)
db.view('workout', 'exercise', q).query(function(err, values){
// use pluck method from underscore to retrieve data
var keys = _.pluck(values, 'id');
console.log("Keys: " + keys);
//fetch multiple documents based on the 'keys' object
db.getMulti(keys, null, function(err, results){
console.log('Results: ' + results);
var workouts = [];
for (var prop in results) {
workouts.push(results[prop].value);
}
reply(workouts);
});
});
}
};
var getMusclegroup = {
handler: function (req, reply) {
var q = {
descending: true,
stale: false
};
db.view('workout', 'exercise', q).query(function(err, values){
var keys = _.pluck(values, 'id');
db.getMulti(keys, null, function(err, results){
var muscleGroups = [];
for (var prop in results) {
console.log(typeof results);
console.log(results[prop].value.workout);
muscleGroups.push(results[prop].value.workout);
}
reply(muscleGroups[0]);
});
});
}
};
var sendWorkout = {
handler: function(req, reply){
var d = new Date();
var cd = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear();
console.log(req.method); // getting a post method - OK
console.log(req.body); // returns undefined
// defines unique key for data
var key = cd;
console.log(key);
// adds payload to database
db.add(key, req.body, function(error, results){
if (error) {
console.log("Coushbase error: " + error);
reply(error + "\n");
}
console.log(results);
reply(req.body);
});
}
};
var workoutNew = {
handler: function (req, reply) {
reply.file("static/html/workoutForm.html");
},
};
module.exports = [
{method: 'GET', path: '/static/{param*}', config: { handler: { directory: { path: 'static'}}}},
{method: 'GET', path: '/', config: landingPage},
{method: 'GET', path: '/workouts', config: getWorkouts},
{method: 'GET', path: '/workouts/musclegroup', config: getMusclegroup},
{method: 'GET', path: '/newworkout', config: workoutNew},
{method: 'POST', path:'/newworkout/workout', config: sendWorkout}
];
This is my server module:
var Hapi = require('hapi');
var path = require('path');
var Joi = require('joi');
var rs = require('./lib/modules/routes.js');
var config= { };
var server = Hapi.createServer(process.env.PORT || 8080, config);
server.route(rs);
server.start(function(){
console.log("Server started: " + server.info.uri);
});
module.exports = server;
This is my html form:
<div id="forms">
<form id="workout-form" name="workout-form" action="newworkout/workout" method="POST">
<div class="workouts">
<label for="exercise" class="labels">Exercise</label><input type="text" name="exercise" id="exercise" placeholder="Which exercise?" autofocus />
<label for="musclegroup" class="labels">Muscle-Group</label><input type="text" name="musclegroup" id="musclegroup" placeholder="Which muscle-group?" />
<div class="sets">
<label for="reps" class="labels">Reps</label><input type="text" name="reps" id="reps" class="reps-column" placeholder="How many reps?" />
<label for="kilos" class="labels">Kg's</label><input type="text" name="kilos" id="kilos" class="kilos-column" placeholder="How much Kg?" />
</div>
<hr>
</div>
<button id="add-set"class="add-buttons" type="button"><i class="fa fa-plus-circle fa-2x"></i></button>
<button id="add-exercise" class="add-buttons" type="button"><i class="fa fa-arrow-circle-down fa-2x"></i></button>
<button id="submit-workout" type="submit" name="submitbutton"><strong>Save Workout</strong></button>
</form>
</div>
Just replace req.body with req.payload:
var path = require('path');
var _ = require('underscore');
var couchbase = require('couchbase');
//Connect to database.
var db = db || new couchbase.Connection({host: 'localhost:8091', bucket: 'default'}, function(err) {
if (err) {
console.log('Connection Error', err);
} else {
console.log('Connected!');
}
});
console.log(db);
//We have a pending connection to the test database running on localhost.
//We now need to get notified if we connect successfully or if a connection error occurs
var landingPage = {
handler: function(req, reply) {
reply.file('index.html');
}
};
var getWorkouts = {
handler: function (req, reply) {
// set options for databse query
var q ={
descending: true,
stale: false
};
// show multiple exercises - db.view(designDocument, viewName, options)
db.view('workout', 'exercise', q).query(function(err, values){
// use pluck method from underscore to retrieve data
var keys = _.pluck(values, 'id');
console.log("Keys: " + keys);
//fetch multiple documents based on the 'keys' object
db.getMulti(keys, null, function(err, results){
console.log('Results: ' + results);
var workouts = [];
for (var prop in results) {
workouts.push(results[prop].value);
}
reply(workouts);
});
});
}
};
var getMusclegroup = {
handler: function (req, reply) {
var q = {
descending: true,
stale: false
};
db.view('workout', 'exercise', q).query(function(err, values){
var keys = _.pluck(values, 'id');
db.getMulti(keys, null, function(err, results){
var muscleGroups = [];
for (var prop in results) {
console.log(typeof results);
console.log(results[prop].value.workout);
muscleGroups.push(results[prop].value.workout);
}
reply(muscleGroups[0]);
});
});
}
};
var sendWorkout = {
handler: function(req, reply){
var d = new Date();
var cd = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear();
console.log(req.method); // getting a post method - OK
console.log(req.payload);
// defines unique key for data
var key = cd;
console.log(key);
// adds payload to database
db.add(key, req.payload, function(error, results){
if (error) {
console.log("Coushbase error: " + error);
reply(error + "\n");
}
console.log(results);
reply(req.payload);
});
}
};
var workoutNew = {
handler: function (req, reply) {
reply.file("static/html/workoutForm.html");
},
};
module.exports = [
{method: 'GET', path: '/static/{param*}', config: { handler: { directory: { path: 'static'}}}},
{method: 'GET', path: '/', config: landingPage},
{method: 'GET', path: '/workouts', config: getWorkouts},
{method: 'GET', path: '/workouts/musclegroup', config: getMusclegroup},
{method: 'GET', path: '/newworkout', config: workoutNew},
{method: 'POST', path:'/newworkout/workout', config: sendWorkout}
];
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.