Having trouble pulling the data from a mongoose promise. I want to find a set of users from mongoose using an appropriate ID and passing the result along a promise chain.
The query is pulling the right data from the database. When I nest the query inside of a promise chain and then attempt to pass along the result, my console.log shows [Function (anonymous)]
. Is there an appropriate structure for pulling the data from MongoDB using mongoose and then passing that data along a promise chain?
Promise chain:
addItem(guildId, items, timeCreated) {
return new Promise((resolve, reject) => {
// other functionality omitted for brevity
resolve(guildId, items, timeCreated);
}).then((guild, item, timeCreate) => {
findGroupUsers(guild).then((response) => {
return new Promise((resolve, reject) => {
console.log(response.userId);
resolve(response);
});
});
Mongoose query:
const findGroupUsers = async (guildId) => {
const members = await EngagementTracking.find({ guildId: `${guildId}` }).exec();
console.log(members);
return members;
};
The verified answer successfully pulls the data from the query inside of addItem. To continue and pass the result of the query along chain, I did the following:
addItem(guildId, items, timeCreated) {
return new Promise((resolve, reject) => {
//other functionality
resolve(guildId, items, timeCreated);
}).then((guild, items, timeCreate) => {
return findGroupUsers(guild).then((response) => {
return new Promise((resolve) => { resolve(response); });
});
}).then((data) =>{// other functionality //});
CodePudding user response:
You function add item seem a bit strange you should do this instead:
addItem(guildId, items, timeCreated) {
return new Promise((resolve, reject) => {
// other functionality omitted for brevity
resolve(guildId, items, timeCreated);
}).then((guild, predict, timeCreate) => {
return findGroupUsers(guild).then((response) => {
console.log(response.userId);
return response;
});
you don't need to return a new promise inside a .then also be warn that you should return your promise (you didn't return findGroupUser)
at the end you should have a addItem.then(/do something/) or an await