不填充嵌套数组的所有引用对象

问题描述 投票:0回答:1

我正在使用以下项目:

    "@nestjs/core": "^7.0.0",
    "@nestjs/mongoose": "^7.0.0",
    "mongoose": "^5.9.12",
    // ...
    "typescript": "^3.7.4",

使用mongoose / mongoDB配置:

      uri: MONGO_DB_URI,
      useUnifiedTopology: true,
      useNewUrlParser: true,
      useFindAndModify: false,
      useCreateIndex: true,

我正在尝试为此模型构建简单CRUD

export const ContactSchema = new mongoose.Schema(
  {
    source_id: { type: String, required: true },
    firstName: { type: String, trim: true },
    lastName: { type: String, trim: true },
    phones: [
      {
        number: {
          type: String,
          required: true,
          unique: true,
          validate: {
            validator: function(value) {
              const phoneNumber = parsePhoneNumberFromString(value)
              return phoneNumber && phoneNumber.isValid()
            },
          },
        },
        type: {
          type: String,
          default: function() {
            return parsePhoneNumberFromString(this.number).getType() || "N/A"
          },
        },
        code: {
          type: Number,
          default: function() {
            return parsePhoneNumberFromString(this.number).countryCallingCode || undefined
          },
        },
        national: {
          type: Number,
          default: function() {
            return parsePhoneNumberFromString(this.number).nationalNumber || undefined
          },
        },
      },
    ],
    email: { type: String, unique: true, required: true, lowercase: true, trim: true },
  },
  { timestamps: true },
)

ContactSchema.plugin(mongoosePaginate)

[像每个CRUD应用程序一样,我愿意有fildAll()fildOne()路由返回给定Contact的主体他的所有信息包括其电话号码列表。所以我用了:

  // ...
  async findAll(): Promise<Contact[]> {
    return this.contactModel.find()
    // then I add
    .populate('phones')
  }

  async findBySourceId(id: string): Promise<Contact> {
    return this.contactModel.findOne({ source_id: id })
    // then I add
    .populate('phones')
  }
  // ...

所有信息都很好地保存在数据库中,并且没有丢失的数据(两个电话都没有),而且我敢肯定,即使没有添加.poplate('x'),它也可以开始工作,但是在某个地方发生了变化,并且它现在返回了未填充的电话阵列

现在返回:

    {
        "_id": "5ebc22072e18637d84bcf6f0",
        "firstName": "Maher",
        "lastName": "Boubakri",
        "phones": [],
        "email": "[email protected]",
        // ...
    }

但是,它应该返回:

    {
        "_id": "5ebc22072e18637d84bcf6f0",
        "firstName": "Maher",
        "lastName": "Boubakri",
        "phones": [
            {
                "_id": "5ebc22072e18637d8fd948f9",
                "number": "+21622123456",
                "code": 216,
                "type": "MOBILE",
                "national": 22123456,
            }
        ],
        "email": "[email protected]",
        // ...
    }

注意:很明显,MongoDB为每个电话对象生成_id,但它不是参考对象。

任何想法都会很有帮助,

谢谢。

mongodb typescript mongoose nestjs mongoose-populate
1个回答
1
投票

populate用于使用引用来连接两个(或更多)集合”>

这里您没有任何参考,因此您不需要它

仅使用find()而不使用populate

© www.soinside.com 2019 - 2024. All rights reserved.