【发布时间】:2018-12-03 13:09:42
【问题描述】:
我正在寻找(但找不到任何)优雅的解决方案,如何在 Mongoose 模型 Person 中使用虚拟属性 fullName。
Person.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PersonSchema = new Schema(
{
firstName: {type: String, required: true, max: 100},
lastName: {type: String, required: true, max: 100}
}
);
PersonSchema
.virtual('fullName')
.get(function () {
return this.firstName + ' ' + this.lastName;
});
module.exports = mongoose.model('Person', PersonSchema);
实际上我可以访问 fullName,但不知道如何将其添加到结果对象中。
app.js
const express = require('express');
require('./connectDB');
const Person = require('./Person');
const app = express();
app.get('/', async (req, res) => {
const result = await Person.find();
result.map((person) => {
console.log('Virtual fullName property: ', person.fullName);
// console print:
// Jane Smith
});
console.log('All returned persons: ', result);
// console print:
// [{ _id: 5ad9f4f25eecbd2b1c842be9,
// firstName: 'Jane',
// lastName: 'Smith',
// __v: 0 }]
res.send({result});
});
app.listen(3000, () => {
console.log('Server has started at port 3000');
});
所以,如果您对如何使用虚拟机有任何想法,请发布
解决方案(感谢 Jason)
在模型导出之前将此代码添加到 Person.js:
PersonSchema
.set('toObject', { getters: true });
【问题讨论】: