简体   繁体   English

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

[英]Relationship between two schemas in mongodb using mongoose

I have two schemas first one is countrySchema which has country id and name: Below is the schema code: 我有两个模式,第一个是countrySchema,它具有国家/地区ID和名称:以下是模式代码:

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

Another schema is stateSchema which has state id and state name: below is the schema code: 另一个模式是stateSchema,它具有状态ID和状态名称:以下是模式代码:

var Schema = mongoose.Schema;

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

Now, in stateSchema i want to have state_id, country_id which is actually coming from the countrySchema and the state_name. 现在,在stateSchema中,我想要有state_id,country_id,这实际上是来自countrySchema和state_name。 How do I do this ? 我该怎么做呢 ?

You can add the country_id as follows and refer the country module in your state module with ObjectId of the country. 您可以如下添加country_id,并在状态模块中使用国家/地区的ObjectId引用国家/地区模块。 Then you have to use the objectId which created by mongoose for the particular country as the country_id of stateSchema. 然后,您必须使用由猫鼬为特定国家/地区创建的objectId作为stateSchema的country_id。

countrySchema countrySchema

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

stateSchema stateSchema

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

Try This One.. 试试这个

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

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


var stateSchema = new Schema({
        state_id:String,
        state_name:String,
        country: { type: Schema.Types.ObjectId, ref: 'countryArray' },

});
var states = mongoose.model('states',stateSchema);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM