我有一个case
集合,其中有一个名为status
(整数)的字段,其有效值为0、1、2、4和8,分别表示“新建”,“在制品”,“已解决” ”,“取消”和“关闭”。
所以,在猫鼬语法中,它可能类似于:
const caseSchema = new Schema({
createdOn: Date,
subittedBy: String,
status: Number,
...
});
const statusSchema = new Schema({
value: Number,
description: String
});
这是组织数据的好方法吗?如何进行查询以检索status
字段中正确填充了description
的案件?
答案 0 :(得分:0)
这是一种确定方法。您可以使用$lookup进行查询。看起来像这样:
db.getCollection('<YourCasesColName>').aggregate([
{ $match : { 'status' : 1 } }, // or { $in: [1,2,3] },
{
$lookup: {
from: '<YourStatusColName>',
localField: 'status',
foreignField: 'value',
as: 'statusDoc',
}
}
])
另一种方法是通过ObjectId添加reference to the actual status,以便在这种情况下,您将存储对实际Status对象的引用,而不是数字,从而具有更好的引用完整性。但是,您仍然需要执行类似的查询才能一举两得。所以这就是我在说的:
const caseSchema = new Schema({
createdOn: Date,
subittedBy: String,
status: { type: mongoose.Schema.Types.ObjectId, ref: 'Status' },
// ^ now your status hows reference to exactly the type of status it has
});
const statusSchema = new Schema({
value: Number,
description: String
});
So the actual data would look like this:
// Statuses
[{
_id: <StatusMongoObjectID_1>,
value: 1,
description: 'New'
},{
_id: <StatusMongoObjectID_2>,
value: 2,
description: 'New'
}]
// Cases
[{
_id: <MongoObjectID>,
createdOn: '<SomeISODate>',
subittedBy: '<SomeString>',
status: <StatusMongoObjectID_1>
},
{
_id: <MongoObjectID>,
createdOn: '<SomeISODate>',
subittedBy: '<SomeString>',
status: <StatusMongoObjectID_2>
}]