使用mongoose在mongodb中的两个模式之间的关系

时间:2018-10-08 09:03:04

标签: node.js mongodb mongoose-schema

我有两个模式,第一个是countrySchema,它具有国家/地区ID和名称: 下面是模式代码:

var countrySchema = new Schema({
        country_id:String,
        country_name:String
});
var countryArray = mongoose.model('countryArray',countrySchema);

另一个模式是stateSchema,它具有状态ID和状态名称: 下面是模式代码:

var Schema = mongoose.Schema;

var stateSchema = new Schema({
        state_id:String,
        state_name:String,
});
var states = mongoose.model('states',stateSchema);

现在,在stateSchema中,我想要有state_id,country_id,它实际上来自countrySchema和state_name。我该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以如下添加country_id,并在状态模块中使用国家/地区的ObjectId引用国家/地区模块。然后,您必须使用由猫鼬为特定国家/地区创建的objectId作为stateSchema的country_id。

countrySchema

var countrySchema = new Schema({
        _id:Schema.Types.ObjectId,
        country_id:String,
        country_name:String
});
var countryArray = mongoose.model('countryArray',countrySchema);

stateSchema

var stateSchema = new Schema({
        _id:Schema.Types.ObjectId,
        state_id:String,
        country_id: {Schema.Types.ObjectId, ref:'countryArray'},
        state_name:String,
    });

答案 1 :(得分:0)

尝试这个。.

<script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="/wordpress-slider-plugin.js"></script>