【问题标题】:Collection2 removes object propertiesCollection2 删除对象属性
【发布时间】:2016-02-03 20:02:06
【问题描述】:

这是我的简化集合及其架构:

Comments = new Mongo.Collection('comments');

Comments.schema = new SimpleSchema({
    attachments: {type: [Object], optional: true},
});

Comments.attachSchema(Comments.schema);

这是我的简化方法:

Meteor.methods({
    postComment() {         
        Comments.insert({
            attachments: [{type:'image', value:'a'}, {type: 'image', value:'b'}]
        });
    }
});

调用该方法后,这是我在 MongoDB 中得到的文档:

{
    "_id" : "768SmgaKeoi5KfyPy",
    "attachments" : [ 
        {}, 
        {}
    ]
}

数组中的对象没有任何属性! 现在,如果我将此行注释掉:

Comments.attachSchema(Comments.schema);

再次调用该方法,插入的文档现在看起来是正确的:

{
    "_id" : "FXHzTGtkPDYtREDG2",
    "attachments" : [ 
        {
            "type" : "image",
            "value" : "a"
        }, 
        {
            "type" : "image",
            "value" : "b"
        }
    ]
}

我必须在这里遗漏一些基本的东西。请赐教。 我正在使用最新版本的 Meteor (1.2.1)。

【问题讨论】:

  • blackbox: true 添加到架构中的属性定义中。

标签: meteor meteor-collection2 simple-schema


【解决方案1】:

来自simple-schema docs

如果您有一个 Object 类型的键,该对象的属性也将被验证,因此您必须在架构中定义所有允许的属性。如果这是不可能的,或者您不想验证对象的属性,请使用 blackbox: true 选项跳过对对象内所有内容的验证。

因此,您需要将 blackbox:true 添加到附件选项中。

Comments.schema = new SimpleSchema({
    attachments: {type: [Object], optional: true, blackbox: true},
});

【讨论】:

  • 就是这样!简单的模式不应该抛出错误而不是默默地删除对象属性吗?
猜你喜欢
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 2017-03-12
  • 2020-07-08
相关资源
最近更新 更多