javascript - Mongoose 如何通过 findOne 在文档中获取嵌套对象
问题描述
我需要在某个文档(按用户 ID 搜索)中获取一个嵌套对象,该文档内部也有一个对象(不能保证该对象将是同一个对象)。
我的用户模型是:
const mongoose = require('mongoose');
const { bool } = require('@hapi/joi');
const monitoringSchema = new mongoose.Schema({
type: Object,
default: {}
})
const hubSchema = new mongoose.Schema({
hubID: {
type: String,
default: ""
},
isSetup: {
type: Boolean,
default: false
},
monitoring: {
type: monitoringSchema
}
}, {strict:false})
const finalUserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
max: 255
},
email: {
type: String,
required: true,
max: 255,
},
password: {
type: String,
required: true,
min: 10,
max: 1024,
},
date: {
type: Date,
default: Date.now
},
isVerified: {
type: Boolean,
default: false
},
hub: {
type: hubSchema
}
}, {strict:false});
module.exports = mongoose.model('User', finalUserSchema);
或者它的布局:
_id: "id"
isVerified: true
username: "nathan"
email: "email@email.com"
hub:
hubID: "id"
monitoring: // WHOLE OBJECT I NEED TO RETREIVE
exampleObject:
exampleValue: exampleKey
我有一组需要更新的用户 ID,我尝试了以下查询:
for(i in usersToUpdate){
User.findOne({_id: usersToUpdate[i], "hub.monitoring": {}}, {}, callbackResponse);
function callbackResponse(err, data){
if(err) return console.log(err)
console.log(data)
}
}
但它null
作为数据返回,所以显然查询是错误的。我知道错误是:
{_id: usersToUpdate[i], "hub.monitoring": {}}
进一步来说:
"hub.monitoring": {}
我{}
用来在监控中引用一个对象,引用未知对象并取回它的值的正确引用是什么,比如通配符?我试过了:
{_id: usersToUpdate[i], "hub.monitoring": Object}
它仍然不起作用。我看过这个答案,但是他们引用了一个他们已经知道的值,比如名字?
解决方案
您可以尝试使用 findOne 的 2 对象形式,其中第一个对象是查询,第二个对象是您想要返回的内容的投影。
User.findOne({_id: usersToUpdate[i]}, {"hub.monitoring": {$exists: true}}, callbackResponse);
function callbackResponse(err, data){
if(err) return console.log(err)
console.log(data)
}
这样,如果监控对象存在,就会返回该对象。
推荐阅读
- javascript - 无法在数组内的对象中添加属性
- python - 抓取图像并保存 jpg
- c# - 为什么这段代码不能让我的播放器跳转到给定的vector3
- machine-learning - 如何为 ML.NET 中的图像分类模型训练创建 .tsv 文件?
- http-headers - Istio 添加的 header 会不会太大?
- c++ - 未定义对 `WaterDispenser::getInstance() 的引用
- node.js - Azure Function App TimmerTrigger 执行时出现超时错误
- c# - 即使条目为空,Xamarin 社区工具包输入验证也为真
- microsoft-teams - 当我尝试在团队桌面弹出窗口中使用 getUserMedia 时出现“权限被拒绝”错误
- java - 使用相对路径将一个 Maven 项目包含到另一个 Maven 项目中