简体   繁体   中英

Find mongoose objects with pointer

I have a model like this...

var studentSchema = new Schema({
    classroomId: Schema.Types.ObjectId,
    // etc
});

var Student = mongoose.model('Student', studentSchema);

var classroomSchema = new Schema({
    // doesn't matter for this question
});

And I have a method on classroom who's job it is to return students. It seems to work with two different syntaxes...

classroomSchema.methods.students = function() {
    // this works
    return Student.find({ classroomId:this._id });

    // and this also seems to work?
    return Student.find({ classroomId:this });
}

Questions:

  • Why do this and this._id both appear to generate the same results? Is it just syntax sugar?
  • Can I rely on this in general? Like, can I assign an object rather than an object ID to a pointer attribute?
  • Who is providing me this nice feature (if that's what it is), is it mongo or mongoose?

Okay so I did some research on this. Created classrooms and students collections as with some documents as shown below :

在此处输入图片说明

So it seems, the Native MongoDB driver doesn't return anything if we do something like this :

db.collection("classrooms").findOne({_id: 1}, function(err, classroom){
    console.log("Got classroom as : " + JSON.stringify(classroom));
    db.collection("students").find({classroomId: classroom}).toArray(function(err, students){
        if(err) console.log(err);
        else console.log(students);

        //Close connection
        db.close();
    });
});

It returns an empty array.

On the other hand if I do something like this :

db.collection("classrooms").findOne({_id: 1}, function(err, classroom){
    console.log("Got classroom as : " + JSON.stringify(classroom));
    db.collection("students").find({classroomId: classroom._id}).toArray(function(err, students){
        if(err) console.log(err);
        else console.log(students);

        //Close connection
        db.close();
    });
});

Then I get an array containing 3 students as are in my students collection with classroomId: 1

So I suppose this is the magic done by mongoose and NOT mongodb.

Also not quite sure if you can rely on this in general.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM