我有我的用户架构:
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
date: { type: Date, default: Date.now },
active: { type: Boolean, default: false }
});
我想创建一个请假状态架构。只有一位用户可以提供所有请假状态的数据。我想将每个休假状态与相应的用户架构ID关联。我尝试了如下的离开状态架构:
const leaveSchema = new Schema({
leave: [
{
email: { type: String, required: true },
month: { type: String, required: true },
year: { type: Number, required: true },
earnedleave: { type: Number },
sickleave: { type: Number },
festivalleave: { type: Number },
compoff: { type: Number }
}
]
});
我如何将我的emailid与userschema相关联。有可能吗如果是这样,我该如何调整?
答案 0 :(得分:2)
我们无需关联架构即可基于leave
获取user
,您可以为此使用聚合,
db.user.aggregate([
...
{$lookup: {from: "leave", localField: "email", foreignField: "leave.email", as: "leaves"}},
...
]);
还是,如果您想关联两个集合,则必须使用ref
和ObjectId
const leaveSchema = new Schema({
leave: [
{
user: { type: Schema.Types.ObjectId, ref: 'user' }, //Your model name as reference
email: { type: String, required: true },
month: { type: String, required: true },
year: { type: Number, required: true },
earnedleave: { type: Number },
sickleave: { type: Number },
festivalleave: { type: Number },
compoff: { type: Number }
}
]
});