My question is this:
How could I fit multiple images into a single object? I mean, suppose I have in an application a model created from a project, which will have different properties, but one of them is images. In which I want it to be an array to be able to introduce several images in it. But I can only make it go up one at a time, and when I upload a new one, it covers the previous one. I honestly don't even know where to start. Thanks in advance. All the best. I use connect-multiparty to perform the file upload.
Model file:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ProyectSchema = Schema({
name: String,
description: String,
tecnologies: String,
author: String,
file: [String]
});
module.exports = mongoose.model('Image', ImageSchema);
Here is the code with which I upload it:
function uploadImageFile(req, res){
var idProyect = req.params.id;
var file_name = 'No subido';
if (req.files) {
var file_path = req.files.file.path;
var file_split = file_path.split('\\');
var file_name = file_split[2];
var ext_split = file_name.split('\.');
var file_ext = ext_split[1];
if (file_ext == 'png' || file_ext == 'jpg' || file_ext == 'gif') {
Proyect.findByIdAndUpdate(idProyect, { file: file_name }, (err, updatedProyect) => {
if (err) {return res.status(500).send({message: 'Error en el servidor.'});}
return res.status(200).send({proyect: updatedProyect});
});
}else{
res.status(200).send({message: 'La extensión del archivo no es correcta.'});
}
}else{
res.status(200).send({message: 'No has subido ningún archivo.'});
}
}
And here's how I instantiate connect-multiparty, in the project route file, and put it as middleware in the route:
multipart = require('connect-multiparty'),
md_upload = multipart({uploadDir: './uploads/images'});
route:
router.post('/uploadImageFile/:id', [md_auth.ensureAuth, md_upload], ImageController.uploadImageFile);
I don't know if it is possible to upload the files at the same time as the project object is created, and so far I only have an idea of how to upload them once the object is created and edited.
Ok, according to your code, first you define your model indicating that an array of objects will be received:
The file attribute is equivalent to putting:
With this you have already told mongoose that this attribute will have an array with objects and that each object will have an attribute called img which is where the image will be saved, whether encoded or its path.
How do I add images?
From your example, I put the most important part:
Check out the mongoose push documentation and mongo is pretty much similar to javascript push.
I managed to do it correctly, but a new question has arisen, and the fact is that I am going to develop the frontend in Angular 2. If I use this in a nodeJs model:
as property. How do I represent it in the Angular model? that is, when I do the classes, how do I have to do it? Here I do not know where to go to collect information on this exactly.