模型中使用猫鼬模型?"/>
如何在其他模型中使用猫鼬模型?
我有以下两个模型。在用户模型中,我想使用请求数组,在请求模型中,我想使用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();
更多推荐
如何在其他模型中使用猫鼬模型?
发布评论