Javascript Meteor:仅当存在值时才将字段插入MongoDB

Javascript Meteor:仅当存在值时才将字段插入MongoDB,javascript,mongodb,validation,meteor,file-upload,Javascript,Mongodb,Validation,Meteor,File Upload,我有一个表格,封面图片和附件是可选的。但是,目前用户必须填写所有表格。如果没有,meteor将打印警告: 未捕获引用错误:未定义imageIdVar 我理解此错误消息的来源 那么,在将文档插入集合时,如何使字段成为可选字段 我的模板助手: Template.adminNewsEvents.events({ 'change #coverImage': function(evt, temp) { /* FS.Utility.eachFile(event, function(file)

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

未捕获引用错误:未定义imageIdVar

我理解此错误消息的来源

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

我的模板助手:

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:标准包

  • 文件系统

  • 无功var

  • dburles:集合帮助程序


非常感谢您的帮助

您只需在meteor项目中安装即可。然后在添加到数据库之前,检查如下

_.isUndefined(imageIdVar);
无论您的
imageIdVar
attachmentivar
是否包含一些数据,该函数都返回布尔值。因此,如果设置为false,将跳过
insert
方法中的image字段
coverImageId
attachmentivar
。由于
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);

多亏了@Faysal Ahmed,我想出了一个解决方案。您必须在开始时将反应变量设置为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);
    }
});

无论您的
imageIdVar
是否实际通过,请以提交形式尝试
console.log
。@KawsarAhmed:每当有人上传文件时,它都会通过。而且插入工作完美无瑕。但上传图像是可选的。因此,如果用户不上传图像,整个文档将不会被插入:(这意味着,我必须构建4个不同的场景?如果两者都定义了,我会按照我的问题中所示进行。然后,我需要三个其他插入函数:如果两个都没有定义(1),或者如果两个中只有一个被定义(2)+(3)。嗯……没有“$exists”吗用于插入新条目?是的,你可以这样做。或者考虑一个更好的解决方案。而且
$exists
操作符适用于你的db查询,而不是插入值。我找不到更好的解决方案。无论是通过谷歌还是我想一想。我知道
$exists
只是查询。这就是为什么我想知道是否有类似
$exists
用于插入值。我刚刚尝试了您的方法。看起来不错,但我仍然得到完全相同的错误/行为。仅当选择了两个可选字段时,插入才起作用。即使使用u979;.isUndefined(imageIdVar.get())也不会返回任何布尔值,而是返回“未捕获引用错误:未定义imageIdVar”请您在Meteopad中完成您的工作,以便我有空时可以看一看。