【问题标题】:Adding fields to model which derived from Mongoose schema将字段添加到从 Mongoose 模式派生的模型
【发布时间】:2014-12-13 11:29:03
【问题描述】:

我有一个看起来像这样的 Mongoose 架构:

ManifestSchema = new Schema({
entries: [{
            order_id: String,
            line_item: {}, // <-- resolved at run time
            address: {},// <-- resolved at run time
            added_at: Number,
            stop: Number,

        }]

}, {collection: 'manifests', strict: true });

在代码的某个地方我有这个:

Q.ninvoke(Manifests.findById(req.params.id), 'exec')
.then(function(manifest)
{
// ... so many things, like resolving the address and the item information
entry.line_item = item;
entry.address = order.delivery.address;
})

我面临的问题是,如果没有在架构中定义地址和 line_item,当我在运行时解决它们时,它们不会返回给用户,因为它们不在架构中......所以我添加了它们...这导致了我另一个不需要的行为:当我将对象保存回来时,地址和 line_item 都与清单对象一起保存,这是我想避免的。

是否可以在运行时向架构添加字段,但在返回时不保存它们?

我试图在猫鼬中使用“虚拟”,但它们确实提供了我需要的东西,因为我不是从模式创建模型,而是从数据库返回。

【问题讨论】:

    标签: node.js mongodb mongoose schema


    【解决方案1】:

    在您的 manifest Mongoose 实例上调用 toObject() 以创建一个纯 JavaScript 副本,您可以为用户响应添加额外的字段,而不会影响您需要保存的文档:

    Q.ninvoke(Manifests.findById(req.params.id), 'exec')
    .then(function(manifest)
    {
      var manifestResponse = manifest.toObject();
    
      // ... so many things, like resolving the address and the item information
      entry.line_item = item;
      entry.address = order.delivery.address;
    })
    

    【讨论】:

    • 非常感谢!你知道为什么会这样吗?是什么让从 mongoose 返回的实体与“普通 javascript”对象不同?
    • @DanielFlippance 一个关键的区别是 Mongoose 文档的属性是使用 Object.defineProperty 定义的。
    猜你喜欢
    • 2020-07-31
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2021-12-31
    • 1970-01-01
    • 2021-07-20
    • 2015-05-16
    相关资源
    最近更新 更多