Как ссылаться на другую коллекцию на вставке?
Я пытаюсь понять, как взять изображение (файл с помощью CollectionFS) и вставить идентификатор изображения в поле Мои элементы imageId
:
Библиотека/Коллекции/items.js
Items = new Mongo.Collection("items");
Items.attachSchema(new SimpleSchema({
name: {
type: String,
label: "Name",
},
userId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
autoform: {
type: "hidden",
label: false
},
autoValue: function () { return Meteor.userId() },
},
image: {
type: String,
optional: true,
autoform: {
label: false,
afFieldInput: {
type: "fileUpload",
collection: "Images",
label: 'Select Photo',
}
}
},
imageId: {
type: String
}
}));
Библиотека/Коллекции/images.js
if (Meteor.isServer) {
var imageStore = new FS.Store.S3("images", {
accessKeyId: Meteor.settings.AWSAccessKeyId,
secretAccessKey: Meteor.settings.AWSSecretAccessKey,
bucket: Meteor.settings.AWSBucket,
});
Images = new FS.Collection("Images", {
stores: [imageStore],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
}
// On the client just create a generic FS Store as don't have
// access (or want access) to S3 settings on client
if (Meteor.isClient) {
var imageStore = new FS.Store.S3("images");
Images = new FS.Collection("Images", {
stores: [imageStore],
filter: {
allow: {
contentTypes: ['image/*']
},
}
});
}
Сейчас мои правила разрешений:
сервер/allows.js
Items.allow({
insert: function(userId, doc){return doc && doc.userId === userId;},
update: function(userId, doc){ return doc && doc.userId === userId;},
remove: function(userId, doc) { return doc && doc.userId === userId;},
})
Images.allow({
insert: function(userId, doc) { return true; },
update: function(userId,doc) { return true; },
remove: function(userId,doc) { return true; },
download: function(userId, doc) {return true;},
});
Я использую Autoform, поэтому моя форма выглядит следующим образом:
клиент/item_form.html
<template name="insertItemForm">
{{#autoForm collection="Items" id="insertItemForm" type="insert"}}
{{> afQuickField name="name" autocomplete="off"}}
{{> afQuickField name="image" id="imageFile"}}
<button type="submit">Continue</button>
{{/autoForm}}
</template>
Прямо сейчас, когда я выбираю просмотр и выбираю образ, он будет находиться в базе данных, и я хочу принять его _id
и разместить его в Item
, который создается впоследствии, но как я могу получить этот конкретный образ? Я понял, что это хороший способ ссылки на изображение.
ОБНОВЛЕНИЕ 1
Выясните, что идентификатор на самом деле скрыт после выбора файла:
<input type="hidden" class="js-value" data-schema-key="image" value="ma633fFpKHYewCRm8">
Итак, я пытаюсь установить ma633fFpKHYewCRm8
как String
в imageId
.
ОБНОВЛЕНИЕ 2
Возможно, одним из способов является использование FS.File Reference?
Ответы
Ответ 1
Я решил ту же проблему довольно просто, после того, как файл вставлен, я просто вызываю метод, который выполняет соответствующее обновление коллекции:
client.html
<template name="hello">
<p>upload file for first texture: <input id="myFileInput1" type="file"> </p>
</template>
lib.js
var textureStore = new FS.Store.GridFS("textures");
TextureFiles = new FS.Collection("textures", {
stores: [textureStore]
});
Textures = new Mongo.Collection("textures");
client.js
Template.hello.events({
'change #myFileInput1': function(event, template) {
uploadTextureToDb('first',event);
}
});
function uploadTextureToDb(name, event) {
FS.Utility.eachFile(event, function(file) {
TextureFiles.insert(file, function (err, fileObj) {
// Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
console.log('inserted');
console.log(fileObj);
//after file itself is inserted, we also update Texture object with reference to this file
Meteor.call('updateTexture',name,fileObj._id);
});
});
}
server.js
Meteor.methods({
updateTexture: function(textureName, fileId) {
Textures.upsert(
{
name:textureName
},
{
$set: {
file: fileId,
updatedAt: Date.now()
}
});
}
});
поскольку вы используете autoForm и simpleSchema, это может быть не так просто, но я предлагаю вам сначала забыть об autoForm и simpleSchema и попытаться заставить его работать с простыми наборами html и по умолчанию.
После того, как все работает, вы можете вернуться к настройке, но будьте осторожны, что может возникнуть больше проблем, когда дело доходит до CollectionFS, особенно когда дело доходит до стиля, сгенерированного autoForm.