javascript - 如何在另一个模型中使用猫鼬模型?
问题描述
我有以下两个模型。在用户模型中,我想使用请求数组,在请求模型中,我想将用户用作属性(没有密码)。我该怎么做?
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.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();
推荐阅读
- reactjs - react.js 中如何使用 localStorage?
- kotlin - Android协程没有完成
- java - FTPClient.retrieveFile 返回 false,但文件仍在下载
- termux - 打开 termux:127|:/data/data/com.termux/files/home 后出错
- vert.x - 如何在 vertx future compose 中使用中间结果?
- r - 使用 batchtools/BatchJobs 在两台 R 服务器上进行并行计算
- python - 我如何将字典的平面展平仅深于 3 个级别
- php - PHP 7.3 升级 - 奇怪行为 mysql 事务
- inheritance - Crystal:如何在 child 中用一种方法实现多个抽象方法?
- maven - 声明式 Jenkins 流水线:如何为不同的存储库迭代同一阶段?