【问题标题】:Trying to understand how mongoose populate or join works试图了解猫鼬如何填充或加入工作
【发布时间】:2016-04-28 17:57:11
【问题描述】:

我只是想看看如何加入不同的收藏。假设我有一个病人集合和医生集合。我想这样做是因为医生可能有很多患者,我不确定是否应该将所有患者放入名为 patients : [] 的模型字段中的对象数组中,或者做我现在尝试练习的事情填充方法猫鼬。

现在我还有一个问题。如果我使用 populate(join) 方法,所有的医生病人都会在一起。我认为这很奇怪,因为听起来个人信息会与不同的人混淆。我知道 populate 通过将 Id 与 ref 关联来将患者与医生关联起来。这是一个好方法吗?

无论如何,我尝试过使用 populate 并失败了。我将向您展示下面的代码。如果你能帮助我按照我描述的方式加入这两个系列,那就太棒了。如果你能解决一些其他问题,那也很好。

我尝试将医生 2 与患者 1 关联起来。

我得到一个错误:

throw new MongooseError.MissingSchemaError(name);
 MissingSchemaError: Schema hasn't been registered for model "Doctor".
Use mongoose.model(name, schema)

代码

var express = require("express");
var app = express();
var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/population");

var db = mongoose.connection;

db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function(){
    console.log("connected")
    var doctorSchema = mongoose.Schema({
        name : String,
        address : String,
        username: String,
        password : String,
        patients : [{type : mongoose.Schema.Types.ObjectId, ref: "Patient"}]
    })
    var patientSchema = mongoose.Schema({
        _doctor : {type: mongoose.Schema.Types.ObjectId, ref : "Doctor"},
        name: String,
        illness : String
    })
    //compiling our schem into a Model. A class where we construct documents
    var Doctor = mongoose.model("doctor", doctorSchema );
    var Patient = mongoose.model("patient", patientSchema);

    var doctor1 = new Doctor({name : "doc1", address :"add1", username :"user1", password : "pass1"})
    console.log(doctor1.username);

    //creating a patient for doctor2
    var doctor2 = new Doctor({name: "doc2", address : "add2", username : "user2", password : "pass2"});

    doctor2.save(function(err){
        var patient1 = new Patient({
            name : "pat1",
            illness: "high",
            _doctor: doctor2._id
        })

        patient1.save(function(err){
            console.log("saved")
        })      
    })

    Patient.findOne({name : "pat1"})
            .populate("_doctor")
            .exec(function(err, patient){
                console.log("the creator is %s", patient._doctor.name)
            })

    })





app.listen(3000, function(){
    console.log("listening on port: " , 3000)
})

【问题讨论】:

  • 在引用模式时必须给出模型的确切名称。您在模型中定义了医生,在参考中定义了医生
  • @MariyaJames 这对我有帮助,我不再有错误了。谢谢。现在我得到db.doctors.find() -- { "_id" : ObjectId("56a0cb74c5ba46780e4d17c6"), "name" : "doc2", "address" : "ad d2", "username" : "user2", "password" : "pass2", "patients" : [ ], "__v" : 0 } 编辑:“患者”应该是一个空数组
  • 您没有向归档的患者插入任何内容,这就是原因。
  • 我使用 .populate('patients') 将内容插入到患者字段中?我想我希望患者字段具有属于医生的患者的 ObjectId 数组。我还是没有。

标签: javascript node.js mongodb mongoose mongoose-populate


【解决方案1】:

您的代码问题

首先,请在引用时确保正确的型号名称。

var Doctor = mongoose.model("Doctor", doctorSchema ); // rather than doctor
var Patient = mongoose.model("Patient", patientSchema); // rather than patient

其次,patient1保存成功后,再在db中找到。因为save()异步操作。

patient1.save(function(err){
    if (err)
        console.log(err);
    else {
        console.log("saved");
        Patient.findOne({name : "pat1"})
            .populate("_doctor")
            .exec(function(err, patient){
                if (err)
                    console.log(err);
                else {
                    console.log(patient);
                    console.log("the creator is %s", patient._doctor.name);
                }
            });
    }
}); 

数据架构

正如我们所知,要么将patient 作为对doctor 的引用

var doctorSchema = mongoose.Schema({
    patients : [{type : mongoose.Schema.Types.ObjectId, ref: "Patient"}]
});

或者把doctor作为patient的引用

var patientSchema = mongoose.Schema({
    _doctor : {type: mongoose.Schema.Types.ObjectId, ref : "Doctor"},
}); 

他们两个都可以。但是,数据模式应该满足您更有效地查询的要求。

我更喜欢将doctor 作为patient 的参考,因为正如您所说,一位医生可能有更多的患者。 mongodb 文档的最大大小为16 megabytes。如果我们将patient 作为doctor 的引用,则doctor 文档在更多患者情况下可能会更大。

无论如何,您选择哪种架构来满足您的要求是首要考虑因素。

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2015-07-13
    • 2016-10-10
    相关资源
    最近更新 更多