【问题标题】:insert failed: Error: Title is required插入失败:错误:需要标题
【发布时间】:2017-09-11 02:09:34
【问题描述】:

我正在尝试使用以下代码将对象添加到作为集合条目中的键的对象数组中,但我收到了一个奇怪的响应“插入失败:错误:需要标题”。我在流星上使用简单的模式/自动形式。

以前有没有人遇到过这种情况(并有解决方案)?

Template.dashboard.events({
  'click .requestinvite'(e,t) {
    Posts.insert({ _id : $(e.currentTarget).attr('_id')},
    {$push: { invitesRequested : {username : Meteor.userId()} }}
  );
}
});

这是咖啡脚本中相关的简单模式

Schemas.Posts = new SimpleSchema
    title:
        type:String
        max: 60
        optional: true

    content:
        type: String
        optional: false
        autoform:
            rows: 5

    createdAt:
        type: Date
        autoValue: ->
            if this.isInsert
                new Date()

    updatedAt:
        type:Date
        optional:true
        autoValue: ->
            if this.isUpdate
                new Date()

    invitesRequested:
        type: [Object]
        optional: true
        defaultValue: []


    owner:
        type: String
        regEx: SimpleSchema.RegEx.Id
        autoValue: ->
            if this.isInsert
                Meteor.userId()
        autoform:
            options: ->
                _.map Meteor.users.find().fetch(), (user)->
                    label: user.emails[0].address
                    value: user._id

【问题讨论】:

  • 您的简单架构必须有一个必需的标题
  • 是的,似乎简单的架构阻止了插入,您需要允许标题。
  • 请在此处发布您的 SimpleSchema。提供足够的详细信息,以免我们在您的问题上浪费时间。
  • @AnkurSoni 在上面添加了相关的简单模式

标签: javascript meteor meteor-autoform simple-schema


【解决方案1】:

首先,根据正确的 javascript 分配标准,您在代码中犯了错误。

如果您的代码被黑客入侵,并且在没有分配任何 id 的情况下调用了 click 事件怎么办?

您的代码必须如下。

Template.dashboard.events({
  'click .requestinvite'(e,t) {
    var id = $(e.currentTarget).attr('_id');
    if(id){
    Posts.insert(
        { 
            _id : id
        },
        {   
            $push: { 
                    invitesRequested : {username : Meteor.userId()} 
                }
        }
    );
    } else {
        //do something here when you don't have id here, or the `click` event is hacked on UI to work without id'
    }
}
});

由于您的 SimpleSchema 给出了关于 title 字段的错误,如果它不是强制性的,请在定义 title 字段时使用 optional : true

例如

title: {
    type: String,
    label: "Title",
    optional: true   //<---- do this
}

注意:默认情况下,所有键都是必需的。设置optional: true 来改变它。

【讨论】:

  • 这会导致以下错误“插入失败:错误:需要内容”
  • 一连串的事件现在很明显,它似乎试图为帖子创建一个新的补充?我正在尝试推送到 Posts 中现有条目中的邀请请求值数组,为什么要尝试创建新的 Posts 条目?我应该使用不同的函数而不是插入吗?
  • 如果我的回答能帮助你实现你的答案,这是一个谦虚的请求。接受答案会激励我们回答越来越多的人,从而引导他们学习新事物。
【解决方案2】:

答案是使用 Posts.update。但是 Ankur Soni 的帖子让我找到了解决问题的正确方向。

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 2016-07-06
    • 2015-02-13
    • 2019-08-16
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多