我正在寻找(并且找不到任何)优雅的解决方案如何在 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);
Run Code Online (Sandbox Code Playgroud)
实际上我可以访问 fullName,但不知道如何将其添加到结果对象中。
应用程序.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');
});
Run Code Online (Sandbox Code Playgroud)
因此,如果您对如何使用虚拟有任何想法,请发布
解决方案(感谢 Jason)
在模型导出之前将此代码添加到Person.js中:
PersonSchema
.set('toObject', { getters: true });
Run Code Online (Sandbox Code Playgroud)
参考架构文档:
要让所有虚拟值显示在
console.log输出中,请将toObject选项设置为{ getters: true }
默认情况下,从 mongoose 文档到 POJO 的转换中不包含虚拟路径。console.log导致 mongoose 自动调用此转换。
使用此选项更新PersonSchema将使虚拟包含在记录的输出中:
const PersonSchema = new Schema({
firstName: {
type: String,
required: true,
max: 100
},
lastName: {
type: String,
required: true,
max: 100
}
}, {
getters: true
});
Run Code Online (Sandbox Code Playgroud)
可以在此处toObject找到完整的选项列表。
| 归档时间: |
|
| 查看次数: |
5597 次 |
| 最近记录: |