我可以使用 multer-gridfs-storage 将文件上传到我的 MongoDB,但我无法将文件与我的“客户”模式相关联。基本上,每个客户都应该拥有三种类型的文件:网络、电子邮件和密码文件。每个文件都是一个 .txt。我的最终目标是为每个客户提供一个展示页面,并能够通过 :id 找到客户,然后填充客户的三个文件。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const customerSchema = new Schema({
name: {
type: String
},
address: {
street: String,
city: String,
state: String,
zip: String,
},
fileID:
{
type: Schema.Types.ObjectId,
}
}, { timestamps: true });
module.exports = mongoose.model("Customer", customerSchema);
// Create mongo connection
const conn = mongoose.createConnection(process.env.MONGO_DB_URL);
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('customers');
});
// Create storage engine
const storage = new GridFsStorage({
url: process.env.MONGO_DB_URL,
file: (req, file) => {
return {
filename: file.originalname,
bucketName: 'customers'
};
}
});
const upload = multer({ storage });
post route to upload files
router.post('/upload', upload.single('file'), (req, res) => {
res.json({ file: req.file });
});