gpt4 book ai didi

javascript - meteor :仅当值存在时才将字段插入 MongoDB

转载 作者:行者123 更新时间:2023-11-30 16:19:20 24 4
gpt4 key购买 nike

我有一个表单,其中 coverImage 和附件是可选的。但是,目前用户必须填写所有表格。如果不是, 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:标准包

  • cfs:文件系统

  • react 变量

  • dburles:collection-helpers

非常感谢任何帮助。

最佳答案

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

_.isUndefined(imageIdVar);

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

更好的方法

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);

关于javascript - meteor :仅当值存在时才将字段插入 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com