簡體   English   中英

無法查詢子文檔貓鼬

[英]Unable to query sub document mongoose

我有這樣的架構,我正在嘗試使用_id從數組中獲取文檔。 這是我正在進行的第一個Mongo項目,請幫助我如何實現這一目標。 我基本上想檢索與id對應的子文檔,並在其中更新一些數據。

    var PhoneSchema = new mongoose.Schema({
            type: String,
            number: String
        });

        var StudentSchema =  new mongoose.Schema({
            name: String,
            dept: String,
            phone: [PhoneSchema]    
        });

var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);

我嘗試了以下方法,但沒有一個起作用。

方法1:當我在控制台中嘗試相同操作時,它給了我父文檔以及與phoneId對應的子文檔

Student.findOne({"phone._id":new mongoose.Schema.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err,     student)       { 

}

方法2:根據貓鼬文檔來檢索子文檔,在這種情況下,我得到了異常提示,說電話未定義

Student.phone.Id(phoneId); 

我已通過從以下查詢中刪除架構來解決此問題

Student.findOne({"phone._id":new mongoose.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err,     student)       { 

}

我試圖解決您的要求。 以下代碼完成了這項工作。

var PhoneSchema = new mongoose.Schema({
            type: String,
            number: String
        });

var StudentSchema =  new mongoose.Schema({
            name: String,
            dept: String,
            phone: [PhoneSchema]    
        });

var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);

var newPhone = new Phone({
    type: 'ios', number: '9030204942'
});

var newStudent = new Student({
    name:'Pankaj',
    dept:'cse',
    phone:newPhone
});

// newStudent.save(function(err, ph) {
//     if (err) return console.error(err);

// });

Student.findOne({"phone._id":mongoose.Types.ObjectId('587e6409e06170ba1708dc21') },{_id:0,phone:1}, function(err,     phone)       { 
        if(err){
            console.log(err)
        }
        console.log(phone);
});

找到以下截圖與結果 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM