【问题标题】:Meteor: Insert field into MongoDB only if a value existsMeteor:仅当值存在时才将字段插入 MongoDB
【发布时间】:2016-02-01 00:45:26
【问题描述】:

我有一个表单,其中封面图像和附件是可选的。但是,目前用户必须填写所有表格。如果没有,meteor 会打印警告:

Uncaught ReferenceError: imageIdVar is not defined

我了解此错误消息的来源。

那么,如何在将文档插入集合时使这些字段成为可选字段?

我的模板助手:

Template.adminNewsEvents.events({
    'change #coverImage': function(evt, temp) {
    /* FS.Utility.eachFile(event, function(file) {
      Images.insert(file, function (err, fileObj) {
        // Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
        if (err) throw err;
      });
    }); */

        var image = event.target.files[0];

        // Insert the image into the database
        // getting the image ID for use in the course object
        var imageObject = Images.insert(image);

        // The image id is stored in the image object
        var imageId = imageObject._id

        // Create a reactive var to be used when the course is added
        imageIdVar = new ReactiveVar(imageId);

    },
    'change #attachment': function(evt, temp) {
    /* FS.Utility.eachFile(event, function(file) {
      Images.insert(file, function (err, fileObj) {
        // Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
        if (err) throw err;
      });
    }); */

        var attachment = event.target.files[0];

        // Insert the image into the database
        // getting the image ID for use in the course object
        var attachmentObject = Attachments.insert(attachment);

        // The image id is stored in the image object
        var attachmentId = attachmentObject._id

        // Create a reactive var to be used when the course is added
        attachmentIdVar = new ReactiveVar(attachmentId);

    },
    'submit form': function (evt, temp) {
        evt.preventDefault();
        NewsEvents.insert({
            title: $('#title').val(),
            description: $('#description').val(),
            type: $('input[name=netype]:checked').val(),
            coverImageId: imageIdVar.get(),
            attachmentId: attachmentIdVar.get(),
            createdAt: new Date ()
        });

        $('#title').val('');
        $('#description').val('');
        $("input:radio").removeAttr("checked");

        console.log("done");
    }
});

我考虑过使用 if 语句来检查 var 是否真实,但这似乎很麻烦。

我正在使用以下软件包:

  • cfs:standard-packages

  • cfs:文件系统

  • reactive-var

  • dburles:collection-helpers

高度赞赏任何帮助。

【问题讨论】:

  • 在提交表单中尝试console.log,无论您的imageIdVar 是否真的通过了。
  • @KawsarAhmed:每当有人上传文件时,它就会被传递。并且插入工作完美无缺。但上传图片是可选的。因此,如果用户不上传图像,则不会插入整个文档:(

标签: javascript mongodb validation meteor file-upload


【解决方案1】:

您所要做的就是在您的流星项目中安装underscoreJS。然后在添加到数据库之前像这样检查

_.isUndefined(imageIdVar);

无论您的imageIdVarattachmentIdVar 是否有一些数据,这都会返回布尔值。因此,如果您得到错误,您将在 insert 方法中跳过图像字段 coverImageIdattachmentIdVar。由于MongDB 是无模式的,因此如果没有这些字段,插入不会有问题。

更好的方法

var temp ={};
temp.title = $('#title').val();
// and for other variables also
if(!_.inUndefined(imageIdVar.get())) {
    temp.coverImageId = imageIdVar.get()
}
// you'll do also for attachment ID. then you'll insert the temp variable in the insert method
NewsEvents.insert(temp);

【讨论】:

  • 也就是说,我必须构建 4 个不同的场景?如果两者都被定义,我会按照我的问题所示进行。然后,我需要其他三个插入函数:如果两个都没有定义 (1),或者如果两个中的一个被定义 (2) + (3)。嗯……没有“$exists”用于插入新条目吗?
  • 是的,您可以这样做。或考虑更好的解决方案。 $exists 运算符适用于您的数据库查询,不适用于插入值
  • 我找不到更好的解决方案。既不是通过谷歌,也不是当我想到它时。我知道$exists 仅供查询。这就是为什么我想知道是否有类似$exists 的东西用于插入值。
  • 我刚试过你的方法。看起来不错,但我仍然得到完全相同的错误/行为。 inserting only works when the two optional fields are selected.即使使用 _.isUndefined(imageIdVar.get()) 也不会返回任何布尔值,而是“未捕获的 ReferenceError: imageIdVar is not defined”
  • 请你在meteorpad做你的工作,以便我有空的时候看看。
【解决方案2】:

感谢@Faysal Ahmed,我想出了一个解决方案。您必须在开始时将 ReactiveVar 设置为 false

imageIdVar = new ReactiveVar(false);
attachmentIdVar = new ReactiveVar(false);

Template.adminNewsEvents.events({
    'change #coverImage': function(evt, temp) {
        var image = event.target.files[0];
        var imageObject = Images.insert(image);
        var imageId = imageObject._id

        if (imageId) {
            imageIdVar = new ReactiveVar(imageId);
        }
    },
    'change #attachment': function(evt, temp) {
        var attachment = event.target.files[0];
        var attachmentObject = Attachments.insert(attachment);
        var attachmentId = attachmentObject._id

        if (attachmentId) {
            attachmentIdVar = new ReactiveVar(attachmentId);
        }   
    },
    'submit form': function (evt, temp) {
        evt.preventDefault();

        var temp = {};
        temp.title = $('#title').val();
        temp.description = $('#description').val();
        temp.type = $('input[name=netype]:checked').val();
        temp.createdAt = new Date ();

        if (imageIdVar.get()) {
            temp.coverImageId = imageIdVar.get();
        }

        if (attachmentIdVar.get()) {
            temp.attachmentId = attachmentIdVar.get();
        }

        NewsEvents.insert(temp);
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多