Meteor将字符串数组插入collection2

时间:2016-06-30 07:36:47

标签: mongodb meteor meteor-collection2 simple-schema

我正在努力将字符串数组插入到mongo db集合中。

它出现错误insert failed: Error: Address must be a string

修改

我正在为CC和Attendees生成动态表单字段,并且需要将这些值保存在数组中。

这里是jQuery片段:

$(function(){
  $(document).on('focus', 'div.form-group-options div.input-group-option:last-child input', function(){
    var sInputGroupHtml = $(this).parent().html();
    var sInputGroupClasses = $(this).parent().attr('class');
    $(this).parent().parent().append('<div class="'+sInputGroupClasses+'">'+sInputGroupHtml+'</div>');
  });
  $(document).on('click', 'div.form-group-options .input-group-addon-remove', function(){
    $(this).parent().remove();
  });
});

html:

<form class="row form-horizontal newMeeting"> 
  <div class="form-group form-group-options col-xs-11 col-md-3" id="cc">
    <div class="input-group input-group-option col-xs-12">
      <input type="text" name="option[]" class="form-control" id="cc" placeholder="CCs">
      <span class="input-group-addon input-group-addon-remove">
        <span class="glyphicon glyphicon-remove"></span>
      </span>
    </div>
  </div>

  <div class="form-group form-group-options col-xs-11 col-md-3">
    <div class="input-group input-group-option col-xs-12">
      <input type="text" class="form-control" id="attendees" placeholder="Attendees">
      <span class="input-group-addon input-group-addon-remove">
        <span class="glyphicon glyphicon-remove"></span>
      </span>
    </div>
  </div>

  <div class="row no-print">
    <div class="col-xs-12">     
      <input type="submit" value="Save" class="btn btn-primary pull-right">
    </div>
  </div>
</form>

我的架构:

Emails = new Mongo.Collection('emails');


EmailSchema = new SimpleSchema({

 "attendeesEmail": {
  type: [Object],
  optional: true
},  
"attendeesEmail.$.address": {
  type: String,
  regEx: SimpleSchema.RegEx.Email
},
ccEmails: {
  type: [Object],
  optional: true
},
"ccEmails.$.address": {
  type: String,
  regEx: SimpleSchema.RegEx.Email
}
});

Emails.attachSchema(EmailSchema);

事件:

Template.form.events({
'submit .newMeeting': function(event) {
var cc = $('#cc').serializeArray();
var attendees = $('#attendees').serializeArray();
});

插入:

Emails.insert({
  attendeesEmail: [{address: attendees}],
  ccEmails: [{address: cc }]
});

console.log(attendees);打印[Object] 错误消息显示insert failed: Error: 0 must be a string

我尝试了很少的解决方案,但无法使其正常运行,任何建议都会受到赞赏。

3 个答案:

答案 0 :(得分:0)

  

.serializeArray()方法创建一个JavaScript对象数组,   准备编码为JSON字符串

所以 cc 与会者 不是字符串

您可以尝试使用toSource()方法:

var cc = $('#cc').serializeArray().toSource();
var attendees = $('#attendees').serializeArray().toSource();

或使用JSON.stringify方法

var cc = JSON.stringify($('#cc').serializeArray());
var attendees = JSON.stringify($('#attendees').serializeArray());

但是toSource方法并不适用于Chrome,IE。它适用于Firefox
API Here

&#13;
&#13;
   <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
    var x = $("form").serializeArray();
    alert(JSON.stringify($("form").serializeArray()));
    $.each(x, function(i, field){
        $("#results").append(field.name + ":" + field.value + " ");
    });
});
});
</script>
</head>
<body>

<form action="">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
</form>

<button>Serialize form values</button>

<div id="results"></div>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以通过更新此类事件来解决问题。

Template.form.events({
  'submit .newMeeting': function(event) {
     var cc = $('#cc').val();
     var attendees = $('#attendees').val();
});

由于serializeArray()方法将您的字符串转换为对象,因此问题正在发生,但如果您仍想使用serializeArray方法,那么您可以这样做

Template.form.events({
  'submit .newMeeting': function(event) {
     var cc = $('#cc').serializeArray().value;
     var attendees = $('#attendees').serializeArray().value;
});

答案 2 :(得分:0)

您明确定义架构的方式是错误的,尤其是attendeesEmailccEmails属性。如果您希望它是一个对象数组,那么您需要明确定义对象键数组,如下所示:

Emails = new Mongo.Collection('emails');

EmailSchema = new SimpleSchema({
    "attendeesEmail": {
        type: [Object],
        optional: true
    },  
    "attendeesEmail.$.address": {
        type: String,
        regEx: SimpleSchema.RegEx.Email
    },
    ccEmails: {
        type: [Object],
        optional: true
    },
    "ccEmails.$.address": {
        type: String,
        regEx: SimpleSchema.RegEx.Email
    }
});

Emails.attachSchema(EmailSchema);

一旦定义了此模式,您就可以使用以下示例作为指导来实现插入。这假设用户在文本输入中输入以分号分隔的电子邮件地址列表。它使用事件处理程序中提供的模板作用域,通过对模板进行作用而使代码更容易出错,这种方法在Meteor中进行表单的方式比较简洁,没有所有全局jQuery引用。

模板代码:

<template name="foo">
    <form id="myform" class="newMeeting">
        <input type="text" name="attendees" />
        <input type="text" name="cc" />
        <input type="submit" id="submit" />
    </form>
</template>

事件处理程序:

Template.foo.events({   
    'submit form': function(event, template) {
        event.preventDefault();

        var attendees = template.find("input[name=attendees]"),
            cc = template.find("input[name=cc]"),
            attendeesList = attendees.split(';').map(function (email){ 
                return { address: email } 
            }),
            ccList = cc.split(';').map(function (email){ 
                return { address: email } 
            });


        // Do form validation

        var data = {
            attendeesEmail: attendeesList,
            ccEmails: ccList
        };

        // Clear form
        attendees.value = "";
        cc.value = "";

        Emails.insert(data, function(err) { /* handle error */ });
    }
});