jsbisht
jsbisht

Reputation: 9649

Issue with Nested query execution in mongoose

I am trying out the following query. I am writing this to get list of documents, for each document i need to run some logic to get the tags list. Using this tag list i update the document with tags list obtained.

I am getting the tags list for 'updateAndPrint' function as blank. I guess its an issue with promise coming into picture.

Here is the query:

DB.todoTable.find()
    .limit(10)
    .exec(function (err, todos) {
        var tags = [];
        for (var todo in todos) {
            var text = todos[todo].text;
            var id = todos[todo]._id;
            console.log(text);
            tags = getTagsList(text);

            (function updateAndPrint(id, tags) {
                DB.todoTable.update({_id: id}, {$addToSet: {tags: {$each: tags}}},
                    function (err, numberUpdated, result) {
                        if (err) throw err;

                        (function printResult(id) {
                            DB.todoTable.findOne({_id: id})
                                .exec(function (err, todo) {
                                    if (err) throw err;

                                    console.dir(todo.tags);
                                });
                        })(id);
                    });
            })(id, tags);

        }
        console.dir(tags);
    });

How can i get this query to run. Or is there a better way to do the same logic.

Edit

'tags = getTagsList(text)' has to be performed before i run update operation.

Upvotes: 0

Views: 68

Answers (1)

Pio
Pio

Reputation: 4062

Use findAndModify instead of update and set the option {new: true}.

UPDATE

You can pass your function to be called as a callback to your findTags, so instead findTags(text) you will have findTags(text, callback), where your callback will be the updateAndPrint function. So when you got all your data in the findTags you can call the callback.

Upvotes: 1

Related Questions