【发布时间】:2022-01-22 07:36:43
【问题描述】:
在将此标记为“已回答”(或类似内容)之前请仔细阅读(不仅仅是标题),因为我确实研究了很长时间,但还没有找到解决方案(我发现了有关查询的问题嵌套数组对象,但不是需要填充的嵌套数组文档)。
我正在使用最新版本的 NodeJS 和 Mongoose。
为了说明,我将使用这两个模型来帮助描绘我的目标:
// Sections
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
const sectionSchema = new Schema({
_id: Schema.Types.ObjectId,
name: { type: String, required: [true, 'Name is required.']},
});
module.exports = mongoose.model('Section', sectionSchema);
还有:
// Departments
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
const departmentSchema = new Schema({
_id: Schema.Types.ObjectId,
name: { type: String, required: [true, 'Name is required.']},
sections: [{ type: Schema.Types.ObjectId, ref: 'Section' }]
});
module.exports = mongoose.model('Department', departmentSchema);
考虑我将这些存储在数据库中:
// Departments
_id: ObjectId("61b0f1971ad3890000000001")
name: "Department 1",
sections: [ObjectId("61b26a3fb756a1000000000b"), ObjectId("61b26a3fb756a1000000000c")]
_id: ObjectId("61b0f1971ad3890000000002")
name: "Department 2",
sections: [ObjectId("61b26a3fb756a1000000000a"), ObjectId("61b26a3fb756a1000000000c")]
_id: ObjectId("61b0f1971ad3890000000003")
name: "Department 3",
sections: []
_id: ObjectId("61b0f1971ad3890000000004")
name: "Department 4",
sections: [ObjectId("61b26a3fb756a1000000000b")]
// Sections
_id: ObjectId("61b26a3fb756a1000000000a")
name: "Section A"
_id: ObjectId("61b26a3fb756a1000000000b")
name: "Section B"
_id: ObjectId("61b26a3fb756a1000000000c")
name: "Section C"
现在,我要做的是获取不包含任何部分或名称为“Section A”的部分的部门(作为来自前端的过滤器的文本)。
Department.find(criteria).select('name').populate('sections').then(results => {
console.log('Departments: ', results.map(r => r.name));
});
// Should print:
Departments: [ Department 2, Department 3 ]
对于标准,我尝试了许多不同的方法,但到目前为止似乎都没有奏效(我总是得到零结果)。下面的一个例子:
const criteria = {
$or: [
{ 'sections': [] },
{ 'sections': { '$elemMatch': { name: 'Section A' }}},
]
};
我认为这是因为在查询填充数组之前测试了 criteria。如果这是正在发生的事情,那么最好的解决方法是什么?我想避免分别查询这两个文档然后匹配结果。 应该有办法一次性做到这一点。有任何想法吗?提前致谢。
【问题讨论】:
标签: node.js arrays nested document populate