Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

selecting required fields in mongodb using monk

I am able to retrieve only selected fields in mongodb using Monk using the below method

collection.find({}, 'Name Age -_id', function (e, docs) {
    res.json(docs);
});

This works fine, but i am facing issues when i add one more option in the query it throws fn should be a function error as it expects third parameter to be success callback function

I get this error when i try

collection.find({},{limit:5}, 'Name Age -_id', function (e, docs) {
        res.json(docs);
    });

I tried using on success function but still got the same error

collection. find({} ,  { limit: 5 }, 'Name Age -_id').on('success', function (e, docs) {
        res.json(docs);
    });

Upvotes: 1

Views: 253

Answers (3)

IrfanAnwar
IrfanAnwar

Reputation: 79

I would prefer a cleaner and more readable way to do this,

        query1={'userType':'mobile'}; //What to select
         query2={limit : 2, fields : "name age _id"} //limit and fields to select
        collection.find(query1,query2,
        function(error,mobile_users){
            if(error)
                response.send(error)
            else{
                response.send(mobile_users);
            }
        });

hope it helps

Upvotes: 1

Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

Just in case anyone wants to select fields including _id, you can try the below solution

collection. find({},{ limit: 5 , fields : 'Name Age _id'}, function (e, docs) {
        res.json(docs);
    });

This will select and return only Name, Age and _id fields

Upvotes: 0

Hiren S.
Hiren S.

Reputation: 2832

collection.find({ },  { limit : 5, fields : "Name Age -_id"  },   function (err,data) {
 res.json(docs);
});

Upvotes: 3

Related Questions