【发布时间】:2021-11-24 12:58:18
【问题描述】:
我想根据一个部门的薪水获得前两名员工,
部门架构::
const departmentSchema = mongoose.Schema({
name: {
type: String
},
employee_id: [{ type: mongoose.Schema.Types.ObjectId, ref: 'employee' }]
})
员工架构 ::
const employeeSchema = mongoose.Schema({
name: {
type: String,
},
salary : {
type: Number
}
})
假设我在部门架构中有文档为 ::
{
"_id":ObjectId("615851c162a012f82cc5bdf6"),
"name":"abc",
"employee_id":[
ObjectId("615852d062a012f82cc5d54d"),
ObjectId("6158530462a012f82cc5d9c8"),
ObjectID("6158530462a012f82cc8e1b9")
]
}
在员工中记录为 ::
{
"_id":ObjectId("615852d062a012f82cc5d54d"),
"name":"john",
"salary":12345
}
{
"_id":ObjectId("6158530462a012f82cc5d9c8"),
"name":"smith",
"salary":999
}
{
"_id":ObjectId("6158530462a012f82cc8e1b9"),
"name":"Alex",
"salary":99999
}
基于此,我想根据薪水获取前两名员工的详细信息。
为此,我尝试如下:
await department.aggregate([
{ $match : { name : 'abc' } },
]).populated('employee_id')
但它抛出错误填充不是一个函数。我如何才能像我在 MySQL 中非常熟悉但不熟悉 mongodb 一样工作?如果有人需要任何进一步的信息,请告诉我。
预期响应为 ::
[
{
"_id":ObjectId("6158530462a012f82cc8e1b9"),
"name":"Alex",
"salary":99999,
department: abc
},
{
"_id":ObjectId("615852d062a012f82cc5d54d"),
"name":"john",
"salary":12345,
department: abc
}
]
【问题讨论】:
-
我认为如果你的
employeeSchema有departmentId字段而不是你的departmentSchema有employeeIdIMO 的数组字段会更好 -
你的函数是
populated。应该是populate -
填充也给出同样的错误
-
我想与部门匹配,然后从该部门获取供应商列表。
-
这个问题似乎是 1) mongoose 填充语法错误和 2) mongodb 查询以获得前 2 名员工的混合体。对于问题 2),您可能会看到这个Mongo playground 看看它是否适合您的需要。
标签: node.js mongodb mongoose mongodb-query