【发布时间】: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