0

我有两个模式:

诊所:

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,我希望在记录中获得完整的程序对象。我试试这个查询:

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

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

4

1 回答 1

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;

希望这有帮助。

于 2013-11-09T10:50:11.853 回答