【问题标题】:Popular a field of a schema with a schema that is inside an array (Moongose)使用数组内的模式流行模式的字段(猫鼬)
【发布时间】:2021-02-16 17:38:36
【问题描述】:

我需要获取指向city_id的数据,它是一个Schema,它链接到另一个Schema的数组。

This is the Schema called Companies and I need to get information about the city

{
"_id": "5fa1484a34a032ac5687b1c2",
"name": "Company",
"address": "Address",
"email": "email@email.com",
"phone": 123456789,
"city_id": "5fa147b607f466ac1d536bd0",
"__v": 0

},

现在,这是城市模式。我有一个位置架构,其中包含一个国家关系:

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);

这是 Country Schema,其中包含 City 关系:

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"
    },

如何获取城市信息?非常感谢。

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query


    【解决方案1】:

    试试这个:

     locationModel.findOne({_id:"5fa147b607f466ac1d536bce"})
          .populate({ path:"locations",{path:"cities"}})
          .exec((err,location) => {
                   if(err) reject(err);
                   return resolve(location);   
                })`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 2023-03-13
      • 2019-10-30
      • 2012-02-02
      • 2014-02-15
      • 2015-05-15
      相关资源
      最近更新 更多