Ajay Srikanth
Ajay Srikanth

Reputation: 1185

Unable to query sub document mongoose

I've schema like this and i', trying to get the document from the array using _id. This is my first Mongo project that I'm working, please help me how can I achieve the. I basically want to retrieve the sub document corresponds to the id and update some data in that.

    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);

I've tried the following ways, but none of them are working.

Method 1: When I tried the same in the console it is giving me the parent document along with the sub document that corresponds to the phoneId

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

}

Method 2: As per the mongoose documentation to retrieve sub documents, in this case I'm getting exception saying phone is undefined

Student.phone.Id(phoneId); 

I've fixed this by removing Schema from the below query

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

}

Upvotes: 0

Views: 429

Answers (1)

Pankaj kumar Panigrahi
Pankaj kumar Panigrahi

Reputation: 761

i tried to solve your requirement. The following code did the job.

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);
});

Find the following screenshot with result enter image description here

Upvotes: 2

Related Questions