Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Node q loop through array and append data

Say I have the following array:

[{id: 1, name: 'Hello', otherTableId: 2}];

Now I wish to loop through all of these arrays and get some data from my MongoDB that I want to append to a new array that is then returned.

How would I do this with q ?

Here is what I have so far, but I don't know what to replace the foreach with:

router.route('/api/conversations')
.get(function (req, res) {
    mongoose.models.conversation.find({users: {$all: [req.query.id]}}, function (err, conversation) {
        if (err) {
            res.status(500).send(err)
        }
        else {
            var returnArray =[];
            conversation.forEach(function (x) {

            })
        }
    });
});

My schemas

var conversation = mongoose.Schema({
    users: Array
});

var user = mongoose.Schema({
    username: String,
    password: String,
    firstname: String,
    lastname: String,
    is_active: Boolean,
    user_type: Number
});

What I want to return is basically a list of conversation and their users.

Like this: [{conversation_id: String, userOne: Object, userTwo: Object}]

However I'm not sure that is possible.

Upvotes: 0

Views: 77

Answers (1)

Christian Landgren
Christian Landgren

Reputation: 13783

First of all, in mongoose you population logic built in, which means you should be able to add something like this:

conversation
.find({users: {$all: [req.query.id]})
.populate('otherTableId')
.exec(function (err, conversations) {
  // now the convesations array should have followed the link from 'otherTableId' if you have defined the ref in the schema.
})

If I interpret the question more generic I would think you are asking about the Promise library Q which should have support for the Promise.all method. I'm using the standard ES6 implementation below but please feel free to find corresponding methods in Q.

const ids = [1,2,3,4]
const promises = ids.map(id => mongoose.models.childTable.findOne(id))
Promise.all(promises).then(array => {
   // here you will find the array containing the objects
})

Upvotes: 1

Related Questions