【发布时间】:2018-06-03 16:21:19
【问题描述】:
每当我调用客户端时,它都会在客户端 [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
});
【问题讨论】:
-
client在您的架构中定义为一个数组。如果您只期望一个结果,则不要将其定义为数组。即client: { type: Schema.Types.ObjectId, ref: 'Client', required: true }。你得到一个数组,因为这是你告诉它存储的。 -
有没有办法将它定义为数组以外的东西?我还没有看到它以任何其他方式完成
-
这就是我刚刚向您展示的方法。不过,您实际上需要像这样“存储”文档。您当前的文档现在都将有一个包含一个成员的数组,因此您需要将它们全部重写为一个值。
-
哦,我明白了!我没有注意到你没有包括括号。我一天中的大部分时间都花在这上面,你马上就能看到!
标签: mongoose mongoose-schema mongoose-populate