How to use promises in mongoose - node.js

By runnig the below code,i can see the values in my console,but the response i got is empty ,i thoink it may be because of promises....
My code,
exports.getcatlist = function(req, res) {
var params = req.params,
item = {
'status': '1',
'type': 'categories'
};
Categories.find(item,function (err, result) {
if (err) {
return
}
if (result) {
var profiles = [];
var categories_to_get = []
var categories = []
for (var i in result) {
var id = result[i]._id;console.log(id)
var id = id.toString();
categories_to_get.push(get_category(id, profiles))
}
Promise.all(categories_to_get)
.then(() => {
console.log('final vals'+categories_to_get)
res.json({status: 'success', data: profiles});
})
} //end of if loop
else {
response = {
status: 'fail',
data: []
};
}
})
function get_category(id, profiles) {
var profiles = [];
return new Promise(function (resolve, reject) {
var item = {
'categoryid' : id,
'status': '1',
'type': 'topics',
};
Categories.count(item,function (err, result) {
if (err) {
reject(err)
return
}
if (result == []) {
profiles.push(result)
resolve()
}
if (result) {
profiles.push(result)
resolve()
} else {
reject()
}
});
})
}
}
By runnig the above code,i can see the values in my console,but the response i got is empty
`{
"status": "success",
"data": []
}`
I am not sure why i am getting my data as empty,can anyone please suggest help...

Sorry but your code is pretty messy, here's solution and clean approach, i would strongly suggest to use async library for things you tryin to accomplish.
//npm install async --save
var async = require('async');
exports.getcatlist = (req, res) => {
var params = req.params;
Categories.find({
status: '1',
type: 'categories'
}, (err, result) => {
if(err)
return res.json({status: 'fail'});
var profiles = [];
async.each(result, (id, cb) => {
Categories.count({
categoryid: id,
status: '1',
type: 'topics'
}, (ierr, val) => {
if(ierr)
return cb(ierr);
profiles.push(val);
cb();
});
}, (eachError) => {
if(eachError)
return res.json({status: 'fail'});
res.json({status: 'success', data: profiles});
});
}
}

Related

FInding difficulty in updating a doc in MERN stack React Native

I don't know where II am missing something in the code as It's working clearly from postman.
my backend Nodejs server function is :
exports.updateFCMToken = (req, res) => {
try {
User.findByIdAndUpdate(
req.params.id,
{
$set: {
fcmToken: req.body.fcmToken
}
},
(err, doc) => {
if (err) {
console.log(err);
res.status(400).send('update FCMToken - Error')
}
return res.status(200).send('FCMToken Updated Successfully')
}
)
}
catch (err) {
console.log(err);
res.status(400).send('server Error - FCMToken')
}
}
From component I am calling the action:
useEffect(() => {
setTimeout(async () => {
dispatch(updateFCMTokenAction());
}, 1000);
}, [])
my action.js: (doc id and fcmtoken are not similar to output shown in code)
export const updateFCMTokenAction = () => {
return async (dispatch) => {
try {
dispatch({ type: userConstants.UPDATE_FCMTOKEN_REQUEST });
getToken();
const fcmToken = await AsyncStorage.getItem('fcmToken');
const user = await AsyncStorage.getItem('user');
const pushToken = {fcmToken};
const id = JSON.parse(user)._id; // output: 63806e0f4dzeb09a2c03f731
console.log('-----------------updateFCMTokenAction--------------');
console.log('updateFCMTokenAction-fcmToken:', pushToken); // output: {"fcmToken": "fv4-4GIWTymgrt7e3klaPs:APA91bGXOLTNfp4-j4dPVDEL-6lDVUA7GWZchwx4j2BlVPOvOsq3pDOk06xkfBE-Q-J6Q4zix8LX-Jf-69Ey2T22aYmbiVD4j4_kMbVlZa8ip1MRtQ-ZDs0hMpno53o7BjmB9Opc-LWR"}
const res = await axiosInstance.post(`/updatefcmtoken/${id}`, pushToken);
console.log('res: ', res);
dispatch({ type: userConstants.UPDATE_FCMTOKEN_SUCCESS, payload: res.data });
} catch (err) {
console.log('push-err: ', err)
dispatch({ type: userConstants.UPDATE_FCMTOKEN_FAILURE, payload: err });
}
}
}
I am getting an error as :
push-err: [AxiosError: Request failed with status code 400]
What am I missing/unable to see here ?
Thank You ,

Express mongoose Query cannot set headers

Does anyone know why this code gives me the error: "Cannot set headers after they are sent to the client"?
Is there something wrong with my Mongoose Queries?
Thanks for your help!!
router.post('/setriskbydate', (req, res) => {
var username = req.body.username;
var from = new Date(req.body.from);
var to = new Date(req.body.to);
var dates = getDates(from, to);
User.findOne({ username: username }, (err, resp) => {
if (err) {
res.send(err);
}
if (resp) {
var rideIds = resp.ride;
for (let i = 0; i < rideIds.length; i++) {
Ride.findOne({ _id: rideIds[i] }, (error, response) => {
if (error) {
res.send(error)
}
if (response) {
var busnumber = response.busnumber
var date = response.date.split('T')[0];
if (dates.includes(date)) {
console.log(response);
Ride.updateMany({ busnumber: busnumber, date: { "$regex": date }}, { risk: "high" }, (er, re) => {
if (er) {
res.send(er);
}
if (re) {
res.send(re);
}
})
}
}
})
}
}
})
})
Make sure to return all your response statements so that the responses aren't sent more than once, including the headers which cannot be set again after a response.
return res.send(err);
...
return res.send(re);
I think I got it.. Because I am in a for loop I cant do res.send() because the function terminates then. I just replaced the last res.send() with something else and it worked.

resolving a promise using mongodb and nodejs

Hello I am new to nodejs and mongodb, i am having trouble resolving my first promise after the second promise has been resolved. I can see the result of my second promise after it is resolved. Here is my code
var getShows = function () {
return new Promise(function (resolve, reject) {
usersdb.find(function (err, result) {
if(err) return console.error(err);
var usersFromCall = result;
var task = function (users) {
return new Promise(function (resolve, reject) {
var user = {
'name': '',
'pages': []
}
user.name = users.show;
console.log(users);
pagedb.find({'show' : user.name}, function (err, resp) {
for(var j = 0 ; j <resp.length; j ++){
var pages = { 'pageId': ''};
pages.pageId = resp[j].pageId;
user.pages.push(pages);
}
console.log(user);
resolve({show: user});
})
});
};
var actions = usersFromCall.map(task);
return Promise.all(actions);
}).then(function () {
resolve()
})
});
};
do i resolve the first promise in a then function after the find?
The following should work:
var getShows = function () {
return new Promise(function (resolve, reject) {
usersdb.find(function (err, users) {
if (err) return console.error(err);
var task = function (user) {
return new Promise(/* ... */);
};
var actions = users.map(task);
Promise.all(actions).then(resolve, reject);
});
});
};
getShows().then(function (results) {
// Prints the result of each task as an array
console.log(results);
});
Looking at your code, it seems .find returns a Promise. So, just for the sake of avoiding the Promise constructor anti-pattern please try the following, I believe it will produce the correct result
var getShows = function() {
return usersdb.find()
.then(result =>
Promise.all(result.map(
users =>
pagedb.find({
show: users.show
})
.then(resp => ({
show: {
name: users.show,
pages: resp.map(item => ({pageId: item.pageId}))
}
}))
)
)
);
};
or the ES5 version
var getShows = function getShows() {
return usersdb.find().then(function (result) {
return Promise.all(result.map(function (users) {
return pagedb.find({
show: users.show
}).then(function (resp) {
return {
show: {
name: users.show,
pages: resp.map(function (item) {
return { pageId: item.pageId };
})
}
};
});
}));
});
};

How to perform forloop in node js

Acoording to the data available ui should get 2 reults but getting only one since i put res.send in the looop so it is getting ended ,can anyone help me out please.......
exports.getrequestsdetails = function(req, res) {
var params = req.params;
console.log(params)
var record = db.collection('requests');
var item = {
"sent_id": params.id,
"status": 1
}
record.find(item).toArray((err, result) => {
if (err) {
return
}
if (result) {
for (var i in result) {
var id = result[i].recieved_id;
var profile = db.collection('profile');
profile.find({
'_id': new ObjectId(id)
}).toArray((err, resp) => {
if (err) {
return
}
if (resp) {
console.log(resp);
} else {}
});
}
res.send(resp);
} //end of if loop
else {
response = {
status: 'fail',
data: []
};
}
});
}
The problem is in getting the profiles. You are using mongodb's find which is asynchronous. Therefore in your for cycle you start fetching the profiles, but then you send out the res.send well before the fetching of the profiles is finished.
The call back from profile.find(... will be executed after the res.send. Apart from this, the resp variable is inside the find callback and you are trying to res.send it outside.
To deal with this, either you use async or promises. See the below code that uses promises.
var Promise = require('bluebird')
exports.getrequestsdetails = function(req, res) {
var params = req.params;
console.log(params)
var record = db.collection('requests');
var item = {
"sent_id": params.id,
"status": 1
}
record.find(item).toArray((err, result) => {
if (err) {
return
}
if (result) {
var profiles_to_get = []
var profiles = []
for (var i in result) {
var id = result[i].recieved_id;
profiles_to_get.push(get_profile(id, profiles))
}
Promise.all(profiles_to_get)
.then(() => {
res.send(profiles);
})
} //end of if loop
else {
response = {
status: 'fail',
data: []
};
}
});
function get_profile (id, profiles) {
return new Promise(function (resolve, reject) {
var profile = db.collection('profile');
profile.find({
'_id': new ObjectId(id)
}).toArray((err, resp) => {
if (err) {
reject(err)
return
}
if (resp) {
profiles.push(resp)
resolve()
} else {
reject()
}
});
})
}
}
How this works is that it creates a list of profiles to find and stores it in the var profiles_to_get = []. The you use Promise.All(profiles_to_get) which will let you do stuff after all the profiles have been fetched.
You can send only one response back to a request.
Define a variable outside the for loop, append records to it and then send it after the for loop has ended.
exports.getrequestsdetails = function(req, res) {
var params = req.params;
console.log(params)
var record = db.collection('requests');
var item = {
"sent_id": params.id,
"status": 1
}
var resList = [];
record.find(item).toArray((err, result) => {
if (err) {
return
}
if (result) {
for (var i in result) {
var id = result[i].recieved_id;
var profile = db.collection('profile');
profile.find({
'_id': new ObjectId(id)
}).toArray((err, resp) => {
if (err) {
return
}
if (resp) {
console.log(resp);
resList[i] = resp;
}
else{
}
});
}
}//end of if loop
else {
resList = {
status: 'fail',
data: []
};
}
res.send(resList);
});
Don't use for loop in asynchronous mode. Use async module instead like below.
var async = require('async');
exports.getrequestsdetails = function (req, res) {
var params = req.params;
console.log(params)
var record = db.collection('requests');
var item = {
"sent_id": params.id,
"status": 1
}
record.find(item).toArray(function (err, result) {
if (err) {
return
}
if (result) {
var list = [];
async.each(result, function (item, cb) {
var id = item.recieved_id;
var profile = db.collection('profile');
profile.findOne({
'_id': new ObjectId(id)
}, function (err, resp) {
if (err) {
return cb();
}
if (resp) {
list.push(resp);
console.log(resp);
return cb();
}
return cb();
});
}, function (err) {
res.send(list);
});
}//end of if loop
else {
response = {
status: 'fail',
data: []
};
}
});
}
You can push all the resp in list array and send after completing loop.
Like this:
exports.getrequestsdetails = function(req, res) {
var params = req.params;
console.log(params);
var record = db.collection('requests');
var item = {
"sent_id": params.id,
"status": 1
};
record.find(item).toArray((err, result) => {
if (err) {
return err;
}
if (result) {
var list = [];
for (var i in result) {
var id = result[i].recieved_id;
var profile = db.collection('profile');
profile.find({
'_id': new ObjectId(id)
}).toArray((err, resp) => {
if (err) {
return err;
}
else{
list.push(resp);
console.log(resp);
if(i===result[result.length-1]){
res.send(list);
}
}
});
}
} //end of if loop
else {
response = {
status: 'fail',
data: []
};
}
});
};
Hope this work for you
You can add all the list in to an array and finally send the data after the loop

Mongoose remove and create in get route

I have a small issue with mongoose, what I am doing is getting data from online rss feeds, parsing it, and passing it to an array, from which I feed a mongoose model, and all this happens in the get route, what I want to accomplish is delete all the data first from the mongoose model and then populate it with the new data, but it always either deletes the data all together, since the parser iterates a few times, or it doesn't delete anything and the data just keeps adding to the model.
Here's my code
'use strict';
const Promise = require('bluebird');
const request = require('request');
const FeedParser = require('feedparser');
const express = require('express');
const router = express.Router();
const xray = require('x-ray')();
var Post = require('../models/post');
var dataArray = [];
router.get('/', function (req, res) {
const fetch = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
return reject(new Error(`Bad URL (url: ${url}`));
}
const feedparser = new FeedParser();
const items = [];
feedparser.on('error', (e) => {
return reject(e);
}).on('readable', () => {
// This is where the action is!
var item;
console.time('loading')
while (item = feedparser.read()) {
items.push(item);
}
}).on('end', () => {
resolve({
meta: feedparser.meta,
records: items
});
});
request({
method: 'GET',
url: url
}, (e, res, body) => {
if (e) {
return reject(e);
} else if (res.statusCode != 200) {
return reject(new Error(`Bad status code (status: ${res.statusCode}, url: ${url})`));
}
feedparser.end(body);
feedparser.on('end', function () {
console.log('Done');
});
});
});
};
Promise.map([
'url',
'url',
'url',
'url'], (url) => fetch(url), { concurrency: 4 }) // note that concurrency limit
.then((feeds) => {
feeds.forEach(feed => {
feed.records.forEach(record => {
dataArray.push(record);
});
});
}).catch(function (error) {
console.log(error);
});
Post.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log('collection removed');
}
});
dataArray.forEach(post => {
Post.create({
title: post.title,
content: post.description,
created: post.date,
image: post['rss:image']['#'],
link: post.link
}, function (err, newPost) {
console.log(newPost.title);
});
});
Post.find({}, function (err, posts) {
if (err) {
console.log(err);
} else {
res.render('index/home', {
posts: posts
});
}
});
});
module.exports = router;
None of this is going to run synchronously. You can do Something like this :
'use strict';
const Promise = require('bluebird');
const request = require('request');
const FeedParser = require('feedparser');
const express = require('express');
const router = express.Router();
const xray = require('x-ray')();
var Post = require('../models/post');
var dataArray = [];
const fetch;
router.get('/', function (req, res) {
Post.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log('collection removed. Starting to fetch Posts from Service');
fetch = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
return reject(new Error(`Bad URL (url: ${url}`));
}
const feedparser = new FeedParser();
const items = [];
feedparser.on('error', (e) => {
return reject(e);
}).on('readable', () => {
// This is where the action is!
var item;
console.time('loading')
while (item = feedparser.read()) {
items.push(item);
}
}).on('end', () => {
resolve({
meta: feedparser.meta,
records: items
});
});
request({
method: 'GET',
url: url
}, (e, res, body) => {
if (e) {
return reject(e);
} else if (res.statusCode != 200) {
return reject(new Error(`Bad status code (status: ${res.statusCode}, url: ${url})`));
}
feedparser.end(body);
feedparser.on('end', function () {
console.log('Done');
});
});
});
};
}
});
Promise.map([
'url',
'url',
'url',
'url'], (url) => fetch(url), { concurrency: 4 }) // note that concurrency limit
.then((feeds) => {
feeds.forEach(feed => {
dataArray = dataArray.concat(feed.records);
/*feed.records.forEach(record => {
dataArray.push(record);
});*/
});
console.log('inserting posts in the collection');
dataArray.forEach(post => {
Post.create({
title: post.title,
content: post.description,
created: post.date,
image: post['rss:image']['#'],
link: post.link
}, function (err, newPost) {
console.log(newPost.title);
});
});
console.log("Fetching posts from the collection");
Post.find({}, function (err, posts) {
if (err) {
console.log(err);
} else {
res.render('index/home', {
posts: posts
});
}
});
}).catch(function (error) {
console.log(error);
});
});
module.exports = router;
I haven't tested this. Please test it on your end. Let me know if there's an error or something.

Resources