【问题标题】:Is it possible to get virtual property in Mongoose query result?是否可以在 Mongoose 查询结果中获取虚拟属性?
【发布时间】: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 });

【问题讨论】:

    标签: express mongoose


    【解决方案1】:

    用于在架构上的快速集 PersonSchema.set("toJSON", { getters: true }); 上将虚拟包含在 res.send() 中。

    【讨论】:

      【解决方案2】:

      参考documentation 获取架构:

      要让所有虚拟对象显示在您的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
      });
      

      toObject 选项的完整列表可以在 here 找到。

      【讨论】:

      • getter: true 和 virtuals : true 在这些选项中有什么区别?有任何想法吗?它们似乎相同,但不同!
      【解决方案3】:

      为了在 mongoose 查询结果中包含虚拟属性,以便您可以从 api 端获取它,请在您的数据模型架构中执行以下操作:

      PersonSchema
          .set('toObject', { getters: true });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-27
        • 1970-01-01
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-29
        相关资源
        最近更新 更多