用指针查找猫鼬对象

时间:2016-02-18 18:14:34

标签: javascript node.js mongodb mongoose

我有这样的模特......

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

我在课堂上有一种方法可以让学生回归。它似乎使用两种不同的语法...

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

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

问题:

  • 为什么thisthis._id似乎都会生成相同的结果?它只是语法糖吗?
  • 我一般可以依赖这个吗?比如,我可以将一个对象而不是一个对象ID分配给指针属性吗?
  • 谁给我提供了这个不错的功能(如果它就是这样),是mongo还是mongoose?

1 个答案:

答案 0 :(得分:2)

好的,所以我对此做了一些研究。创建了教室和学生集合,如下所示的一些文档:

enter image description here

看来,如果我们这样做,Native MongoDB驱动程序也不会返回任何内容:

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

它返回一个空数组。

另一方面,如果我做这样的事情:

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

然后我得到一个包含3名学生的数组,我的学生系列中有使用classroomId:1

所以我想这是mongoose而不是mongodb所做的魔术。

也不太确定你是否可以依赖这一点。

希望这有帮助。