使用 monk 在 mongodb 中选择必填字段

selecting required fields in mongodb using monk

我可以使用以下方法使用 Monk mongodb 中仅检索选定的字段

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

这工作正常,但是当我在查询中添加一个选项时我遇到了问题,它抛出 fn should be a function 错误,因为它期望第三个参数是成功回调函数

我尝试时遇到此错误

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

我尝试使用 on success 函数,但仍然出现相同的错误

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

以防万一有人想要 select 字段包括 _id,您可以尝试以下解决方案

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

这将 select 和 return 只有姓名、年龄和 _id 字段

我更喜欢用更简洁、更易读的方式来做到这一点,

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

希望对您有所帮助