arrays - 难以查询具有多个元素的嵌套数组 Mongoose
问题描述
我已经将文档建模为:
let UserSchema = new Schema({
name: { type: String, required: true, max: 50, unique: true },
email: {type: String, required: true, max: 50, unique: true},
password: {type: String, required: true, max: 20},
monitoringProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
],
controlProject: [
{
projectName: { type: String, required: true, max: 30},
token: { type: String, required: true},
dispositives: [
{
name: { type: String, required: true, max: 15},
value: { type: String, required: true},
token: { type: String}
}
]
}
]
});
例如,在监控项目中,我可以记录太多不同的项目,并且对于每个项目,我可以记录太多的处置。所以,我有嵌套数组。在其他项目中,我只有一个项目和许多处置,我可以列出它们并仅搜索一个处置。但在这种情况下,像这样:
[ { "_id": "5ee18ece1ea5af75bae55f91", "monitoringProject": [ { "dispositives": [ { "_id": "5ee18ef31ea5af75bae55f9c", "name": "Dispositivo 1", "token": "$2b$15$NntmY9ihNZ7R1Vg1WMtmzOSjlfCoKIuHLofF6g5tKXA57WLLc2At2" }, { "_id": "5ee18ef81ea5af75bae55f9e", "name": "Dispositivo 2", "token": "$2b$15$OZB7HbDLvonsv6A71ozW7.yVY2vJOipTCj0AH7XzoafQwwDho.jpm" }, { "_id": "5ee18efc1ea5af75bae55fa0", "name": "Dispositivo 3", "token": "$2b$15$0hpDzNeTO2qJzBVyAHc/UesrnIRi/YpeAlpCLewNhmfl6fe3SEN0i" }, { "_id": "5ee2278d0754817853134bf3", "name": "Dispositivo 4", "token": "$2b$15$ldC5/CyxITPJGUvtXJ.2S.D6a3FBftg6ctQeS4ne/9xpMP5PPiszK" }, { "_id": "5ee2288956fc4c7870044395", "name": "Dispositivo 6", "token": "$2b$15$3rJt.gXEi/gALvrwxVUsWuwF2RUcBmZcoFOQeXwF45ZuKQrB3AGHG" }, { "_id": "5ee6d23d1756b7a8384bcff0", "name": "Dispositivo 7", "token": "$2b$15$C3I9STKJpf9i/7hzhvHEs.IizXpOEmgRTD3hd7ZSdcvATb73Z0zNC" } ], "_id": "5ee18ede1ea5af75bae55f94", "projectName": "Projeto 2", "token": "$2b$15$xaytMbMnGd3BMAGapX8nn.imvkQKetqx0OIlUUyP3gCxlKz/G6DiG" } ] } ]
我只能列出所有的处置。例如,我只想返回“Dispositivo 2”。
我曾经查询:
await User.find({ email: req.body.email, monitoringProject: { $elemMatch: { token: req.body.projecttoken, dispositives: { $elemMatch: { token: req.body.dispositivetoken } } } } }, { "monitoringProject.$.dispositives": 1} )
或者
await User.find({ email: req.body.email, 'monitoringProject.token': req.body.projecttoken, 'monitoringProject.dispositives.token': req.body.dispositivetoken}, { 'monitoringProject.dispositives.$': 1 })
使用 find 或 findOne。我怎样才能只返回我想要的文件?我尝试了很多不同的方法,但没有运气。
解决方案
推荐阅读
- google-oauth - Google API PHP Authentication Invalid Token Format(问题和答案)
- java - Eclipse、JSF、Java 中的 Crud 实现
- java - 更新多个实体的 Spring Data JPA 问题
- unity3d - 视频播放中断最后几秒
- java-8 - 验证在 mockito 中作为参数传递的泛型类型
- azure - Azure Api 连接:更改连接名称
- apache-spark - 如何将 Palantir Foundry 与 Amazon S3 或 HDFS 集成
- r - 使用 xts 对象本身的变量子集 xts 对象
- python - 我的代码正在处理字典列表,例如字符串 typeerror : TypeError: string indices must be integers
- python - AngularJS - Selenium - 如何获取选项标签值