我正在使用第三方库使用Ajax上传文件,并且当它们上传后,我想将文件名存储在mongoDB中。
这是我的架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const uploadSchema = new Schema({
imgName: [{
type: String
}]
});
module.exports = mongoose.model('Upload', uploadSchema);
我尝试在上传的成功回调中执行插入操作:
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();
}
这会将每个图像存储在数据库中的单独记录中,具有其自己的唯一ID,这不是我想要的。例如,如果我上传2张图片,我希望它成为数据库中的一条记录,但我猜应该像这样:
_id: ObjectId("123uashjkalh73")
> imgName: Array
0: "image1.jpg"
1: "image2.jpg"
__v: 0
答案 0 :(得分:1)
所以我认为这里有些事情要解决。
首先,在您的架构中,
const uploadSchema = new Schema({
imgName: [{
type: String
}]
});
注意 imgName
设置为对象数组。如果要使用字符串数组,则可以完全用type: String
跳过对象符号,而用[String]
(https://mongoosejs.com/docs/schematypes.html#arrays)代替。我认为您想要的是以下内容:
const uploadSchema = new Schema({
imgName: [String]
});
如果您要为此创建一个新模型,我将使用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();
}
希望这会有所帮助。