Reputation: 2459
I am using a 3rd party library for uploading files using Ajax and when they have uploaded I want to store the file names in mongoDB.
This is my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const uploadSchema = new Schema({
imgName: [{
type: String
}]
});
module.exports = mongoose.model('Upload', uploadSchema);
I have tried to perform the insert in the success callback for the upload:
if (data.isSuccess) {
const uploaded = uploader.getFileList();
for (const images of uploaded) {
console.log(images.name);
const upload = new uploadModel({
imgName: images.name
});
upload.save();
}
This is storing each image as in individual record in the database with it's own unique ID which isn't what I want. If I for example upload 2 images, I want it to be one record in the database but should look something like this I guess:
_id: ObjectId("123uashjkalh73")
> imgName: Array
0: "image1.jpg"
1: "image2.jpg"
__v: 0
Upvotes: 1
Views: 1431
Reputation: 489
So I think there are a few things that are off here.
First, in your schema,
const uploadSchema = new Schema({
imgName: [{
type: String
}]
});
imgName
is noted set to an Array of objects. If you want an array of strings, you can completely skip the object notation with type: String
and replace it with [String]
(https://mongoosejs.com/docs/schematypes.html#arrays). I think what you want is the following:
const uploadSchema = new Schema({
imgName: [String]
});
If you are trying to create a new model for this, I simplified the code a bit using reduce
if (data.isSuccess) {
const uploaded = uploader.getFileList();
// similar to your loop but i'm just using reduce here. end result is an array of your image names
const images = uploaded.reduce((acc, image) => [...acc, image.name], []);
const upload = new uploadModel({
imgName: images
});
upload.save();
}
Hope this helps.
Upvotes: 2