javascript - Mongoose,使用查找选择特定字段

我正在尝试仅选择一个特定字段

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

为什么???

最佳答案

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

https://stackoverflow.com/questions/24348437/

相关文章:

python - 类型错误 : ObjectId ('' ) is not JSON seriali

mongodb - E : Unable to locate package mongodb-org

linux - 无法连接到服务器 127.0.0.1 shell/mongo.js

arrays - mongodb通过多个数组项查找

node.js - ( Node :3341) DeprecationWarning: Mongoo

javascript - 在NodeJS中获取Mongo数据库中插入文档的_id

mongodb - Mongoose 的 $or 条件的 find 方法无法正常工作

mongodb - 如何使用 Robo 3T 从 MongoDB 导出 JSON

macos - 无法连接到mongodb errno :61 Connection refused

mongodb - 在 mongoDb 中,如何通过索引删除数组元素?