猫鼬返回有关模式的所有字段

Mongoose returning all fields regarding schema

我的数据库中有一个名为 businesses 的集合。我想要做的是查询在我的模式中定义的数据库和特定字段,而不是文档的所有字段。我认为这就是模式首先存在的原因?

架构

var businessSchema = new mongoose.Schema({
    custom_id: String,
    name: String
});

module.exports = mongoose.model('Business', businessSchema);

快递

router.get('/query', function (req, res, next) {
    res.type('json');
    Business.find({custom_id: req.query.custom_id})
        .then(function (data) {
            res.send({data: data});
        }).catch(function (err) {
        return next(new Error(err.message || err));
    })
});

回应

{
   "data":[
      {
         "_id":"5a50ac105a0d8452b0e341e5",
         "custom_id":"1",
         "name":"Dave and Jane",
         "status":"active",
         "verified":true,
         "created":1492727550760,
         "email":{
            "address":"dave_jane@whatever.com"
         }
      }
   ]
}

在架构中我只有 custom_id 和名称,但是无论我定义(或不​​定义)什么字段,当 Business.find 执行时都会返回文档的所有字段。

与架构为空的行为相同,因此返回所有字段。

我最后做的是为 mongoose 模型创建一个静态方法,称为 findBusinesses 而不是在我的路由中调用常规 find 我调用静态方法,自称查找、映射结果和 returns.

这是代码

businessSchema.statics.findBusinesses = function (query) {
    var deferred = Q.defer();
    this.find(query, function (error, data) {
        if (error) return deferred.reject(new Error(error));
        var models = [];
        data.forEach(function(e){
            var b = {
                custom_id: e.custom,
                name: e.name,
                phone: e.phone,
                };
            if(e.email) b.email = e.email.address;
            models.push(b);
        });
        return deferred.resolve(models);     // got it
    });
    return deferred.promise;
};

在select函数中,只需将需要的字段设置为1,不需要的字段设置为0。见下文:

router.get('/query', function (req, res, next) {
    res.type('json');
    Business.find({custom_id: req.query.custom_id}).select({ "name": 1, "_id": 0})
        .then(function (data) {
            res.send({data: data});
        }).catch(function (err) {
        return next(new Error(err.message || err));
    })
});

您可以使用 select 指定要查询的字段 return。

来自文档

Specifies which document fields to include or exclude (also known as the query "projection")

router.get('/query', function (req, res, next) {
    res.type('json');
    Business.find({custom_id: req.query.custom_id}).select({
      name: 1,
      profile_url: 1
    }).then(function (data) {
            res.send({data: data});
        }).catch(function (err) {
        return next(new Error(err.message || err));
    })
});

1 表示将包含该字段。 0表示排除。但不要将两者混用。

您也可以只使用 "string" 来告诉要获取哪些字段以及要排除哪些字段

Business.find().select("name status")

这告诉 mongoose 获取字段“名称”、“状态”但保留所有其他字段