如何在其他模型中使用猫鼬模型?

编程入门 行业动态 更新时间:2024-10-19 14:51:29

如何在其他<a href=https://www.elefans.com/category/jswz/34/1771358.html style=模型中使用猫鼬模型?"/>

如何在其他模型中使用猫鼬模型?

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

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

回答如下:

您可以使用定义为类型本身的模式:

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

如果两个模型都存储在数据库中,并且您可能想进行关联。您可以从另一个模型中引用一个模型。 (请参阅穆罕默德·莱因的答案)

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

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

将会是这样:

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

更多推荐

如何在其他模型中使用猫鼬模型?

本文发布于:2024-05-07 08:19:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755360.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!