人口分布在猫鼬

时间:2013-07-09 10:54:29

标签: mongodb mongoose populate

我有两个模式:

诊所:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var ProcedureSchema = mongoose.Schema({
    name: {
        type: String,
        trim: true,
        required: true
    },

    alias: {
        type: String,
        trim: true,
        required: true
    }
});

var ClinicSchema = mongoose.Schema({
    name: {
        type: String,
        trim: true,
        required: true
    },

    procedures: [ProcedureSchema]
});

module.exports = mongoose.model('Clinic', ClinicSchema);

并记录:

var mongoose = require('mongoose'),
    Patient = require('./patient'),
    User = require('./user'),
    Clinic = require('./clinic'),
    Schema = mongoose.Schema;

var RecordSchema = Schema({
    doctor: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },

    clinic: {
        type: Schema.Types.ObjectId
    },

    date: {
        type: Date
    },

    patient: {
        type: Schema.Types.ObjectId,
        ref: 'Patient'
    },

    procedure: {
        type: [Schema.Types.ObjectId],
        ref: 'Clinic'
    }
});

module.exports = mongoose.model('Record', RecordSchema);

在记录模式中,我存储了所有过程的ID,这是Clinic的子方案 我想在记录中获得完整的程序对象。 我尝试这个查询:

Record.find({}).
    populate('procedures.procedure').
    populate('doctor').
    populate('patient').
    exec(function(err, records) {
        ...
    });

但只获取id数组,而不是对象数组。 哪里有问题?

1 个答案:

答案 0 :(得分:0)

你完全混合了所有方案:

  

填入( 'procedures.procedure')

但是你没有RecordSchema中的程序。即使它是类型错误,你的意思是procedure.procedures - 你在ProcedureSchema中没有过程。

详细了解MongoDB中的引用,尤其是http://docs.mongodb.org/manual/applications/data-models-tree-structures/

尝试使嵌套路径小于2.像这样:

var User,
Procedure,
Clinic,
Patient,
Record;

function defineModels(mongoose, fn) {
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

User = new Schema({
    ...
});

Procedure = new Schema({
    name: { type: String, trim: true, required: true },
    alias: { type: String, trim: true, required: true }
});

Clinic = new Schema({
    name: { type: String, trim: true, required: true },
    procedures: [ProcedureSchema]
});

Patient = new Schema({
    ...
});

Record = new Schema({
    'date': {type: Date, default: Date.now},
    'doctor': {type: ObjectId, ref: 'User'},
    'clinic': {type: ObjectId, ref: 'Clinic'},
    'patient': {type: ObjectId, ref: 'Patient'},
    'procedure': {type: ObjectId, ref: 'Procedure'},
});

mongoose.model('User', User);
mongoose.model('Procedure', Procedure);
mongoose.model('Clinic', Clinic);
mongoose.model('Patient', Patient);
mongoose.model('Record', Record);
fn();
}

exports.defineModels = defineModels;

希望得到这个帮助。