使用populate获取引用文档,但它返回1

时间:2018-06-03 01:30:41

标签: mongoose mongoose-schema mongoose-populate

每当我调用客户端时,它会在客户端[0]中显示客户端文档的完整json。我希望能够调用work.client.name和work.client.url等。很抱歉,如果这是一个重复的问题,我搜索的时间很长,很难找到答案。

工作控制器

exports.work_detail = function(req, res, next) {

    async.parallel({
        work: function(callback) {
            Work.findById(req.params.id)
                .populate('client')
                .exec(callback);
        }
    }, function(err, results) {
        if (err) { return next(err); }
        if (results.work==null) { // No results.
            var err = new Error('Work not found');
            err.status = 404;
            return next(err);
        }
        // Successful, so render.
        console.log(results.work.client.name);
        res.render('work/work_detail', { title: 'Work Details', work:  results.work } );
    });

};

工作模式

var workSchema = new Schema({
    client: [{ type: Schema.Types.ObjectId, ref: 'Client', required: true }],
    time: {
        type: Number,
    },
    work_done: {
        type: Array,
    },
    work_value: {
        type: [{}],
    },
    total: {
        type: Number,
        // set: calculateValue
    },
    work_address: {
        type: String,
    },
    note: {
        type: String,
    }
    }, {
    timestamps: true
});

客户端模型

var clientSchema = new Schema({
    first_name: {
        type: String,
        required: true,
        set: firstToUpper
    },
    last_name: {
        type: String,
        required: true,
        set: firstToUpper
    },
    address: {
        type: String,
        required: false,
    },
    phone: {
        type: Number,
        required: false,
    },
    email: {
        type: String,
        required: false,
        lowercase: true
    },
    note: {
        type: String,
        required: false,
    }}, {
    timestamps: true,
    toObject: { virtuals: true },
    toJSON: { virtuals: true },
});

// Capitalize first letter of each word when called
function firstToUpper (string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// Virtual for client's full name
clientSchema
.virtual('name')
.get(function () {
    return this.first_name + ' ' + this.last_name;
});
// Virtual for clients's URL
clientSchema
.virtual('url')
.get(function () {
    return '/invoice/client/' + this._id
});

1 个答案:

答案 0 :(得分:0)

由Neil Lunn指出,Schema在事故中被包裹在阵中。