1

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);
    });
4

3 回答 3

3
collection.find({ },  { limit : 5, fields : "Name Age -_id"  },   function (err,data) {
 res.json(docs);
});
于 2015-08-24T06:16:42.527 回答
1

我更喜欢更干净、更易读的方式来做到这一点,

        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);
            }
        });

希望能帮助到你

于 2017-01-31T13:13:03.550 回答
0

以防万一有人想选择包括 _id 在内的字段,您可以尝试以下解决方案

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

这将只选择并返回 Name、Age 和 _id 字段

于 2015-08-24T06:49:06.413 回答