I have this controller which fetch data from instagram api.
controller.prototype.getData = function getData(url, tag, callback) {
var clientId = '81e3d3f35c8a4438964001decaa5a31f'
var catchAll = [];
var config = {
'params': {
'client_id': clientId,
'callback': 'JSON_CALLBACK'
}
}
vm.url = 'https://api.instagram.com/v1/tags/' + tag + '/media/recent/';
http.jsonp(url, config)
.then(function(response) {
vm.imageData = vm.imageData.concat(response.data.data);
vm.instagram.storeData(vm.imageData).then(function(response) {
})
var paging = response.data.pagination;
if (paging.hasOwnProperty('next_url')) {
getData(paging.next_url)
} else {
callback.call();
}
})
}
then on node mongodb controller i have this
exports.create = function(req, res) {
var dataObj = req.body;
dataObj.forEach(function(item) {
Data.find({
'id': item.id
}, function(err, data) {
if (err) {
return handleError(res, err);
}
if (data.length == 0) {
Data.create(item, function(err, data) {
if (err) {
return handleError(res, err);
}
});
}
});
});
};
The logic here is that if user is not existing in the collection i will save it. my question is why is it that it takes too long to response if have lets say 300 instagram object ? is there a ways how to do this in optimal performance?
Related
I am using promise and sending the response but with in the .then() function I can't send the response using res.send();
My code is
var express = require ('express'); //EXPRESS Package
var bodyParser = require('body-parser');// get body-parser
var route = express.Router(); //define our app using express
var multer = require('multer');
var validator = require('validator');
var userModel = require('../../model/user.model');
var session = require('express-session');
route.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
route.use(bodyParser.json()); // for parsing application/json
// route.use(bodyParser.json({ type: 'application/vnd.api+json' }))
route.put("/personal/:id", function (req, res) {
data = {};
data['personal_details'] = req.body;
return userModel.update(req.params.id, data).then( function (result) {
// console.lssog(result);
res.send();
}).catch( function ( err ){
res.send(err).status(400);
});
});
// route.put("/contact/:id", function (req, res) {
// userModel.update(req.params.id, "contact_details", req.body).then( function () {
// res.sendStatus(200)
// }).catch( function ( err ){
// res.send(err).status(400);
// });
// });
module.exports = route;
Users Model file is user.model.js which is shown below:
var passwordHash = require('password-hash');
var mongo = require('mongoskin');
var Q = require('q');
var _ = require('lodash');
var randomstring = require('randomstring');
var db = mongo.db('mongodb://127.0.0.1/angulardemo');
db.bind('demotest');
// var hash = bcrypt.hashSync("12345", salt);
var model = {};
model.login = login;
model.create = create;
model.update = update;
model.destroy = destroy;
model.edit = edit;
module.exports = model;
/**
* Create new user
* #param {request data} userData
*/
function create (userData){
var deferred = Q.defer();
db.demotest.findOne({"email" : userData.email}, function (err, user) {
if (err) deferred.reject(err);
if(user){
deferred.reject('Email "' + userData.email + '" is already taken');
}
else{
createUser();
}
});
function createUser() {
var user = _.omit(userData, ['password', 'c_password']);
var hashedPassword = passwordHash.generate(userData.password);
user.password = hashedPassword;
user.api_token = randomstring.generate(50);
user.registration_code = randomstring.generate(10);
user.is_active = 1;
user.is_verified = 1;
db.demotest.insert(user, function (err, doc) {
if (err) deferred.reject(err);
deferred.resolve();
});
}
return deferred.promise;
}
/**
* Login user
* #param {user request data} data
*/
function login(data) {
var deferred = Q.defer();
db.demotest.findOne({"email" : data.email}, function (err, user) {
if (err) deferred.reject(err);
if(!user) deferred.reject("User not found");
if(user && passwordHash.verify(data.password, user.password)){
deferred.resolve(user);
}
else{
deferred.reject("Invalid Credential");
}
});
return deferred.promise;
}
/**
* Update User
* #param {user id} id
* #param {user data} data
*/
function update(id, data){
var deferred = Q.defer();
// validation
db.demotest.findById(id, function (err, user) {
if (err) deferred.reject(err);
if (user.id !== id) {
// username has changed so check if the new username is already taken
db.demotest.findOne(
{ _id: id },
function (err, user) {
if (err) deferred.reject(err);
if (user) {
// username already exists
deferred.reject('User "' + user.username + '" is already taken')
} else {
updateUser();
}
});
} else {
updateUser();
}
});
function updateUser() {
db.demotest.update(
{ _id: mongo.helper.toObjectID(id) },
{ $set: data },
function (err, doc) {
if (err) deferred.reject(err);
deferred.reject("err");
});
}
return deferred.promise;
// var deferred = Q.defer();
// db.demotest.update({_id : mongo.helper.toObjectID(id)}, {$set: data}, function (err, result) {
// console.log(result);
// if (err) deferred.reject(err);
// deferred.resolve("OLLLL");
// });
// return deferred.promise;
}
function destroy() {
}
function edit() {
}
// var insertTestDoc = function (db, callback) {
// //console.log("one"); return ;
// var collection = db.collection('demotest');
// collection.insertOne({"title" : "demotest", "description" : "Lorem Ipsum Sit Emet.", "password" : hash}, function ( err, db ){
// assert.equal(err, null);
// callback();
// });
// }
// var login = function (db, callback) {
// var collection = db.collection('demotest')
// var cursor = collection.findOne({"title" : "demotest"});
// console.log(cursor);
// // cursor.each(function(err, doc) {
// // assert.equal(err, null);
// // if (doc != null) {
// // console.log(doc);
// // } else {
// // callback();
// // }
// // });
// }
// MongoClient.connect('mongodb://localhost/angulardemo', function ( err, db ){
// assert.equal( null, err );
// console.log("Connected to the server correctly");
// login(db, function () {
// db.close();
// });
// // insertTestDoc(db, function () {
// // db.close();
// // });
// });
Please assist thanks
I can think of two possibilities based on what you've shown, one of which depends on the version of mongoose you're using. Actually, the use of mongoose is an assumption on my part, since you never mention it...
The more likely one is that you're never actually connecting to the database. In your code, somewhere, there needs to be a call to mongoose.connect() or mongoose.createConnection() that fires on app startup (or at least before the request hangs that you're seeing).
If you are in fact doing that and just didn't share it, then the next most likely thing is that you're using a version of mongoose before 4.0, in which queries (e.g. .update()) didn't follow the Promise api, and you had call exec() like:
myModel.findOneAndUpdate(req.params.id, data).exec().then(...);
If I'm wrong in my assumption about mongoose, or if both my suggestions are wrong please update your question with the relevant info.
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 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();
});
});
});
});
}
});
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 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
});
});