首页 > 解决方案 > 在响应 node.js Mongoose 中仅发送对象的一个​​属性

问题描述

想要发送我的子类别的标题作为回应。像这样尝试过,但没有得到任何东西,谁能告诉我该怎么做。

exports.Subcategory= (req, res) => {
    var sub = {}
    Subcategory.findById(req.params.id, function (err, subcategory)     {
        console.log(typeof(subcategory))
        res.send({ sub: subcategory.Tittle})
    });
};

这是我的收藏

"_id": "5c398e8fd301362158004fd1",
"Description": "value",
"Slug": "value",
"category_id": "5c398ac7d301362158004fcd",
"UserId": "5c3796cad3013606e8001f9c",
"updated_at": "2019-01-12T06:51:59.000Z",
"created_at": "2019-01-12T06:51:59.000Z"

并从这个'category_id'中找到'category'集合中的类别信息并通过响应发送

标签: node.jsmongoose

解决方案


您将不得不在猫鼬中使用填充尝试像这样在您的 SubCategory 架构中

const SubCategory = new Schema({category_id:{type:String, ref:'Category'}); // to make the relation with Category model


exports.Subcategory= (req, res) => {
    var sub = {}
    Subcategory.find({_id:req.params.id}).populate('category_id').exec((err,data)=>{
       res.send({ data:data});
    });

推荐阅读