【问题标题】:Building API for model that has referenced attribute为具有引用属性的模型构建 API
【发布时间】:2020-04-08 04:22:01
【问题描述】:

所以我的问题是如何显示具有对另一个模型的属性引用的模型的数据?在这个任务中,我有一个具有属性 state 的 Driver 模型,该模型应该引用另一个名为 State 的具有 name 属性的模型。我知道在 mongoose 中引用模型很热门,但我不知道如何构建 API 来创建新的驱动程序并显示它。

下面是我的 Driver 和 State 模型

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let Driver = new Schema({
name: {
    type: String
},
phone: {
    type: String
},
email: {
    type: String
},
deleted: {
    type: Boolean
},
state: { 
    type: Schema.ObjectId,
    Ref: 'State'
}
});

module.exports = mongoose.model('Driver', Driver);

这是国家的模型

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let State = new Schema({
    name: {
        type: String
    }
});

module.exports = mongoose.model('State', State);

目前我的 API 是这样的

driverRoutes.route('/').get(function(req, res){
    Driver.find(function(err, drivers){
        if(err){
            console.log("Error");
        } else {
            res.json(drivers);
        }
    });
});

driverRoutes.route('/:id').get(function(req, res){
    let id = req.params.id;
    Driver.findById(id, function(err, temp){
        res.json(temp);
    });
});

driverRoutes.route('/add').post(function(req, res){
    let temp = new Driver(req.body);
    temp.save()
        .then(temp =>{
            console.log(temp.state);
            res.status(200).json({'driver': 'driver added successfully'});
        })
        .catch(err => {
            res.status(400).send('adding new driver failed');
        });
});

Route with / 是在表格中显示所有 Drivers。

【问题讨论】:

    标签: javascript node.js express mongoose mern


    【解决方案1】:

    将您的 Driver 模型更改为如下所示,

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
        let Driver = new Schema({
        _id: {
            type:Schema.Types.ObjectId
        },
        name: {
            type: String
        },
        phone: {
            type: String
        },
        email: {
            type: String
        },
        deleted: {
            type: Boolean
        },
        state: { 
            type: Schema.Types.ObjectId, //this is the change made
            Ref: 'State'
        }
       });
    
        module.exports = mongoose.model('Driver', Driver);

    第二步是可选的。也就是说,在您的状态模型中,

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    let State = new Schema({
        _id:{
          type:Schema.Types.ObjectId //this is optional however
        },
        name: {
            type: String
        }
    });
    
    module.exports = mongoose.model('State', State);

    这应该会有所帮助。

    【讨论】:

    • 抱歉回复晚了 :) 我同时找到了解决方案,我还想用我当时不知道该怎么做的 State[name] 填充 Driver 模型的状态。对于任何寻找类似内容的人,请访问 mongoose 填充函数文档,您的问题将得到解答:D
    • 太棒了!祝你的项目好运:)
    猜你喜欢
    • 2015-12-03
    • 2020-07-03
    • 1970-01-01
    • 2019-04-25
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多