【发布时间】:2020-10-07 07:18:43
【问题描述】:
我需要在某个文档(按用户 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}
它仍然不起作用。我见过this answer,但是他们引用了一个他们已经知道的值,比如名字?
【问题讨论】:
-
尝试使用
"hub.monitoring": {$exists: true}。 -
如果知道
hubID,你可以匹配"hub.hubID" : <hubID>,然后从javascript结果中提取monitoring对象。 -
@ShridharSharma 它可以工作,但仍然返回整个文档,我只想要返回文档中的
monitoring对象..... -
@ambianBeing 我不会知道
hubID除非我进行多个查询,我想避免这种情况,因为整个代码每天都会在我的数据库中的每个用户上运行...
标签: javascript node.js mongodb mongoose mongodb-query