1

I'm still learning about node.js and mongodb. I'm trying to write simple app with nodejs and mongoose. My mongoose schema:

var todoSchema = new Schema({
  task: String,
  description: String,
  date: Date,
  status: String,
  checklist: Boolean,
  pic: String
});

I have collection named todos I'm trying to get the content of todos using this code:

apiRoutes.route('/todos/detail')
.get(function(req, res){
    Todo.distinct( "pic" ).each(function(doc){
        Todo.find({"pic": doc.pic}, function(err, todo){
        if (err)
            res.send(err);

        var finalResult = [];
        finalResult.push(todo);
        res.send(finalResult);
        });
    });
});

But I got this error:

Object #<Query> has no method 'each'

Any idea to solve this? Really appreciate for the help.

2 Answers 2

3

From what I gather in your question, you don't necessarily need the loop since with the distinct pics array you are iterating over, you are using it to query the collection for each pic, which is essentially equivalent to just querying the whole collection as sending the resulting array of documents returned from the query:

apiRoutes.route('/todos/detail').get(function(req, res){
    Todo.find({"pic": { "$exists": true }}, function(err, todos){
        if (err) res.send(err);
        res.send(todos);
    });
});

Unless you want to get a distinct list of pics, get the todo items with those pics you could try the following approach:

apiRoutes.route('/todos/detail').get(function(req, res){
    Todo.find().distinct('pic', function(error, pics) {
        // pics is an array of all pics
        Todo.find({"pic": { "$in": pics } }, function(err, todos){
            if (err) res.send(err);
            res.send(todos);
        });
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

hi @chridam thank you for your help. it worked. really appreciated it :)
0

For starting you should try with .forEach() instead of .each() first :) Here you can see the forEach doc.

Comments

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.