亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Mongoose 如何通過 findOne 獲取文檔中的嵌套對象

Mongoose 如何通過 findOne 獲取文檔中的嵌套對象

慕哥9229398 2023-04-20 10:23:03
我需要在某個文檔(按用戶 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: trueusername: "nathan"email: "[email protected]"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}它仍然不起作用。我看過這個答案,但是他們引用了一個他們已經知道的值,比如名字?
查看完整描述

2 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

要僅檢索monitoring對象,aggregation可以使用管道。

用于$match過濾和$project輸出/抑制字段。

User.aggregate([

? {

? ? $match: {

? ? ? _id: mongoose.Types.ObjectId(usersToUpdate[i]),

? ? },

? },

? {

? ? $project: {

? ? ? monitoring: "$hub.monitoring",

? ? ? _id: 0,

? ? },

? },

]).exec(callbackResponse);?


查看完整回答
反對 回復 2023-04-20
?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

您可以嘗試使用 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)

}

這樣,如果監控對象存在,就會返回該對象。


查看完整回答
反對 回復 2023-04-20
  • 2 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號