Arrays 常用模式字段,其模式位于数组中(Moongose)
我需要获取引用city_id的数据,city_id是一个模式,它链接到另一个模式的数组 }, 现在,这是城市模式。我有一个位置模式,其中包含一个国家/地区关系:Arrays 常用模式字段,其模式位于数组中(Moongose),arrays,mongodb,mongoose,mongodb-query,Arrays,Mongodb,Mongoose,Mongodb Query,我需要获取引用city_id的数据,city_id是一个模式,它链接到另一个模式的数组 }, 现在,这是城市模式。我有一个位置模式,其中包含一个国家/地区关系: import Country from './countrySchema'; const locationSchema = new Schema({ region: { type: String, required: true, unique: true, dropDup
import Country from './countrySchema';
const locationSchema = new Schema({
region: {
type: String,
required: true,
unique: true,
dropDups: true
},
locations: [Country.schema]
},{ timestamps: true});
const locationModel = model("Location", locationSchema);
import City from './CitySchema';
const countrySchema = new Schema({
country_name: {
type: String,
required: true,
unique: true,
dropDups: true
},
cities: [City.schema]
},{ _id: true, timestamps: true });
const countryModel = model("Country", countrySchema);
这是国家/地区架构,其中包含城市关系:
import Country from './countrySchema';
const locationSchema = new Schema({
region: {
type: String,
required: true,
unique: true,
dropDups: true
},
locations: [Country.schema]
},{ timestamps: true});
const locationModel = model("Location", locationSchema);
import City from './CitySchema';
const countrySchema = new Schema({
country_name: {
type: String,
required: true,
unique: true,
dropDups: true
},
cities: [City.schema]
},{ _id: true, timestamps: true });
const countryModel = model("Country", countrySchema);
这是城市模式:
const citySchema = new Schema({
city_name: {
type: String,
required: true,
unique: true,
dropDups: true
}
},{ _id: true, timestamps: true });
const cityModel = model("City", citySchema);
最后,这看起来像:
"_id": "5fa147b607f466ac1d536bce",
"locations": [
{
"_id": "5fa147b607f466ac1d536bcf",
"country_name": "Colombia",
"cities": [
{
"_id": "5fa147b607f466ac1d536bd0",
"city_name": "Medellín",
"createdAt": "2020-11-03T12:06:14.914Z",
"updatedAt": "2020-11-03T12:06:14.914Z"
},
{
"_id": "5fa147b607f466ac1d536bd1",
"city_name": "Bogotá",
"createdAt": "2020-11-03T12:06:14.914Z",
"updatedAt": "2020-11-03T12:06:14.914Z"
}
],
"createdAt": "2020-11-03T12:06:14.914Z",
"updatedAt": "2020-11-03T12:06:14.914Z"
},
如何获取城市信息??非常感谢。试试这个:
locationModel.findOne({_id:"5fa147b607f466ac1d536bce"})
.populate({ path:"locations",{path:"cities"}})
.exec((err,location) => {
if(err) reject(err);
return resolve(location);
})`