首页 > 解决方案 > 如何在另一个模型中使用猫鼬模型?

问题描述

我有以下两个模型。在用户模型中,我想使用请求数组,在请求模型中,我想将用户用作属性(没有密码)。我该怎么做?

var userSchema = new Schema({
  cartaoCidadao: {
    type: String,
    required: true,
    index: {
      unique: true,
    },
    match: /[0-9]{8}/,
  },
  password: { type: String, required: true },
  role: { type: String },

  estado: { type: String, enum: ["Infetado", "Suspeito"] },
});

var requestSchema = new Schema({
  encaminhado: { type: String },
  pessoaRisco: { type: String },
  trabalhoRisco: { type: String },
  estadoPedido: { type: String },
  resultado: { type: String },
});

标签: javascriptnode.jsexpressmongoosemodel

解决方案


您可以使用定义为类型本身的架构:

var userSchema = new Schema({
    // ...
    requests: {
        type: [requestSchema] // this property type is: array of requests
    }
    // ...
});

如果两个模型都存储在数据库中,并且您可能想要进行关联。您可以从另一个模型中引用一个模型。(见穆罕默德·拉欣的回答)

然后查询您的父模型并将子模型与其关联(https://mongoosejs.com/docs/populate.html

这是一个如何在填充期间排除某些字段的示例: https ://mongoosejs.com/docs/populate.html#query-conditions

它会是这样的:

User.
  find(/* some query */).
  populate({
    path: 'requests',
    select: 'fieldToSelect1 fieldToSelect2' // You can control which fields to include
  }).
  exec();

推荐阅读