首页 > 解决方案 > 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}

它仍然不起作用。我看过这个答案,但是他们引用了一个他们已经知道的值,比如名字?

标签: javascriptnode.jsmongodbmongoosemongodb-query

解决方案


您可以尝试使用 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)
}

这样,如果监控对象存在,就会返回该对象。


推荐阅读