如何加快节点服务

问题描述 投票:0回答:1

我有两个集合categorytypescategories,每个类别类型有多个类别。当我在每个类别索引中获取所有类别详细信息时,应该有一个category_type字段,其中包含category_type的所有详细信息。

我的代码是:

exports.findAllWithParentChild = (req, res) => {
    let resData = [];
    Models.Category.find()
    .then(data => {
        var results = [];
        async.each(data,function(cat,callback) { 
            console.log(cat.categorytype_id)
            Models.CategoryType.findOne({'_id' : mongoose.Types.ObjectId(cat.categorytype_id)},function(err,catType) {
            var obj = cat.toObject();
            obj.category_type = catType;
            results.push(obj);
            callback(err);
        });            
    },
    function(err) {
        if (err) throw err;
        res.send({
            response: true,
            message: "Category deleted successfully.",
            data : results
        });
     });
  });
};

我需要的格式作为回应:

{
        "_id": "5cb78c44ede6452278d13fbe",
        "title": "fhhghgf",
        "description": "hgfhgf",
        "slug": "hgfhgfhgf",
        "categorytype_id": "5cb78ba8ede6452278d13fb6",
        "user_id": "hgfhgfh",
        "status": true,
        "created_at": "2019-04-17T20:27:48.821Z",
        "updated_at": "2019-04-17T20:27:48.821Z",
        "__v": 0,
        "category_type": {
            "_id": "5cb78ba8ede6452278d13fb6",
            "title": "asde",
            "description": "asde",
            "slug": "asde",
            "user_id": "asde",
            "status": true,
            "created_at": "2019-04-17T20:25:12.863Z",
            "updated_at": "2019-04-17T20:25:12.863Z",
            "__v": 0
        }
    },

有没有更好的方法?谢谢你的协助。

node.js mongoose
1个回答
0
投票

用下面的代码更改代码并检查输出

exports.findAllWithParentChild = (req, res) => {
    Models.Category.find({}).
    populate('categorytypes'). 
    exec(function (err, data) {
        if (err) return handleError(err);
        console.log('Success', data);
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.