【问题标题】:Mongoose Model applying multiple functions to a Model ObjectMongoose 模型将多个功能应用于模型对象
【发布时间】:2015-07-01 10:45:36
【问题描述】:

我正在使用 Nodejs Expressjs MongoDB 和 Mongoose 为我从事的小型服务应用程序创建 rest API。

我完成了所有路线,应用了 .find() 等简单的函数 .findOneAndUpdate() 等 喜欢这个:

    router.get('/testTable', function(req, res, next) {
    TestModel.find(function (err, testTableEntries) {
        if (err) return next(err);
        res.send(testTableEntries);
    });
});

很简单。但是,如果我想合并更多的函数,那么只需要一个 mongo 函数 .find()

如果我想怎么办:

 .find().pretty()

或者,如果要汇总,请进行一些计数:

.find().count()
.find({"fieldName": "How many have this value?"}).count()
.find({"fieldName": "How many have this value?"}).count().pretty()

我尝试了类似的方法:

    router.get('/testTable', function(req, res, next) {
    TestModel.find(function (err, testTableEntries) {
        if (err) return next(err);
        res.send(testTableEntries);
    }).count();
});

或者,也许您可​​以建议使用 promise 的无回调解决方案(如 Bluebird),我的第一个想法是:

router.get('/testTable', function(req, res, next) {
    TestModel.find(function (err, next) {
        if (err) return next(err);
    }).then(function (req, res, next) {
        res.send(testTableEntries);
    }).catch(function (err, next) {
        if (err) return next(err);
    });
});    

也许有一些 Mongoose 内置函数可以解决这个问题,我将不胜感激,但知道如何在 Mongoose 模型上一个接一个地调用函数也会很有用。

提前感谢您的任何建议和想法!

【问题讨论】:

    标签: node.js mongodb function mongoose chaining


    【解决方案1】:

    你可以直接拨打.count()

    Test.count({"fieldName": "How many have this value?"},function(err,count) { 
       // count is the counted results
    });
    

    当然 mongoose 中 `.find() 返回的对象是一个数组,所以:

    Test.find({"fieldName": "How many have this value?"},function(err,results) {
        var count = results.length;
    })
    

    或者对于“链接”,您可以使用“查询”.count()

    Test.find({"fieldName": "How many have this value?"})
       .count().exec(function(err,results) {
    })
    

    如果您想要所有可能的“fieldName”值的“计数”,请使用.aggregate()

    Test.aggregate([
        { "$group": {
            "_id": "fieldName",
            "count": { "$sum": 1 }
        }},
    ],function(err,results) {
       // each result has a count
    });
    

    您通常需要从“内部”异步编程中的回调开始思考,而不是“返回”从您的方法调用到“外部”变量的结果。

    【讨论】:

    • 谢谢,效果很好!最终代码是 router.get('/testTable/:someFiledId' , function (req, res) { Model.count({"someFieldId": req.params.someFieldId}).exec(function(err, count) { var jsoncount = {"count": count}; if (err) return err; res.send(jsoncount); }); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2019-06-23
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多