为了账号安全,请及时绑定邮箱和手机立即绑定

猫鼬,使用查找选择特定字段

猫鼬,使用查找选择特定字段

我正在尝试仅选择一个特定的领域exports.someValue = function(req, res, next) {    //query with mongoose    var query = dbSchemas.SomeValue.find({}).select('name');    query.exec(function (err, someValue) {        if (err) return next(err);        res.send(someValue);    });};但是在我的json响应中,我也收到_id,我的文档架构只有两个字段,_id和name[{"_id":70672,"name":"SOME VALUE 1"},{"_id":71327,"name":"SOME VALUE 2"}]为什么???
查看完整描述

3 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

_id除非您明确排除该字段,否则该字段始终存在。使用以下-语法:


exports.someValue = function(req, res, next) {

    //query with mongoose

    var query = dbSchemas.SomeValue.find({}).select('name -_id');


    query.exec(function (err, someValue) {

        if (err) return next(err);

        res.send(someValue);

    });

};

或通过对象显式:


exports.someValue = function(req, res, next) {

    //query with mongoose

    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});


    query.exec(function (err, someValue) {

        if (err) return next(err);

        res.send(someValue);

    });

};


查看完整回答
反对 回复 2019-12-27
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

现在有一种更短的方法:


exports.someValue = function(req, res, next) {

    //query with mongoose

    dbSchemas.SomeValue.find({}, 'name', function(err, someValue){

      if(err) return next(err);

      res.send(someValue);

    });

    //this eliminates the .select() and .exec() methods

};

如果您需要大部分,Schema fields而只想删除几个,则可以在字段前面name加上-。例如"-name",第二个参数中的ex 将不包含name文档中的字段,而此处给出的示例将仅name包含返回的文档中的字段。


查看完整回答
反对 回复 2019-12-27
  • 3 回答
  • 0 关注
  • 903 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信