0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How can i obtain taglist while using findAndModify. 'tags = getTagsList(text)' has to be performed before i run update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.