慕哥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);?

冉冉說
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)
}
這樣,如果監控對象存在,就會返回該對象。
添加回答
舉報
0/150
提交
取消