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

我正在尝试仅选择一个特定的领域


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"}]

为什么???


翻过高山走不出你
浏览 908回答 3
3回答

犯罪嫌疑人X

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

杨__羊羊

现在有一种更短的方法: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包含返回的文档中的字段。
打开App,查看更多内容
随时随地看视频慕课网APP