使用从两个集合node.js中获取的res.send方法发送数据

时间:2019-01-13 05:30:59

标签: node.js mongoose

我有两个集合categoriessubcategories,每个类别都有多个子类别。在subcategories集合中,每个文档都有一个category_id字段。现在我想当我使用subcategory从中获取特定category_id的数据时,获取类别详细信息,这是我的代码,我没有从'data.category_id'得到任何响应 这是我的代码

exports.TopicsBySubcategoryId = (req, res) => {
    Subcategory.findOne({
        _id: req.params.id
    })
    .then(obj => {
        if (obj != null && obj != '') {
            console.log(obj)
            console.log(obj.category_id)
            Category.findOne({
                _id: obj.category_id
                }).then(data => {
                    if (data != null && data != '') {
                        console.log(data)
                        res.send({ response: true, message: 'Data fetched successfully', data:{category : data, subcategory : obj} })
                        return
                    } else {
                        console.log('not found')
                        res.send({ response: false, message: 'Server mmmencountered some error' })
                    }
                }).catch(err => {
                    console.log(err)
                    res.send({ 
                        response: false, 
                        message: 'Server mmmencountered some error !!!' 
                    })
                    return
                })
        } else {
            res.send({ response: false, message: "Server mmmencountered some error !!!" })
        }
    }).catch(err => {
        console.log(err)
        res.send({ response: false, message: 'Server encountered some error !!!' })
        return
    });
};

这是输出

{ _id: 5c398cb7d301362158004fce,
Title: 'dsgds',
Description: 'gdsgsgsg',
Slug: 'sgdsgdsg',
category_id: '5c398ac7d301362158004fcd',
UserId: '5c3796cad3013606e8001f9c',
updated_at: 2019-01-12T06:44:07.000Z,
created_at: 2019-01-12T06:44:07.000Z }
undefined
not found

obj.category_id什么都没有,

subcategory

let SubcategorySchema = new Schema({
    Title: {type: String, required: true},
    category_id: {type: String, required: true},
    Description: {type: String, required: true},
    Slug: {type: String, required: true},
});

category

let CategorySchema = new Schema({
    Title: {type: String, required: true},
    Description: {type: String, required: true},
    Slug: {type: String, required: true},
});

0 个答案:

没有答案