如何在Express中的JSON响应中添加来自不同模型的字段?

时间:2019-06-18 09:45:13

标签: express

我正在开发此快速应用程序,我想知道是否有任何方法可以在JSON响应中添加来自不同架构的字段? 这是代码。
这是第一个模式

const restaurantSchema = mongoose.Schema({
title: { type: String, required: true},
prepration_time: {type: String,required:true},
timings: {type: String,required:true},
listed: {type: Boolean},
});

这是第二个模式

    const menuSchema = mongoose.Schema({
    dish: {type: String,required:true},
    category: {type: String,required:true},
    price: {type: String,required:true},
    restaurant: { type:mongoose.Schema.Types.ObjectId,ref: 'Restaurant' , require: true }

});

我已经使用Schema类型来设置关系,并且我想将菜单模式显示为饭店模式中的字段。

这是路由器功能:

    router.get('',(req,res,next)=>{
    Restaurant.find()
    .then(result =>{
        console.log(result);
        res.status(200).json({
            message: "Fetched",
            restaurants: result
        });
    });    
});

1 个答案:

答案 0 :(得分:0)

const restaurantSchema = mongoose.Schema({
  title: { type: String, required: true},
  prepration_time: {type: String,required:true},
  timings: {type: String,required:true},
  listed: {type: Boolean},
  menu : {type: Schema.types.ObjectId, ref:'menus'}
});

确保 ref 应该是您的收藏名称。将数据添加到restaurant集合时,请确保在menu field的{​​{1}}中添加菜单文档的ID 例如:

restaurant collection

然后像这样查询

{
  title: 'Restaurant name',
  prepration_time: '45 min',
  timings: '12:24pm',
  listed: true,
  menu : '123sfererdfd23422' // _id from menu collection
}