![](/img/trans.png)
[英]I am trying to save latitude and longitude to mongoose model but I am unable to store them
[英]I am trying to store images using Multer and mongoose though data:Buffer
我的架構看起來像這樣
const RecipeSchema = mongoose.Schema({
user: [
{
userName: { type: String, required: true },
userID: { type: String, required: true },
userPicture: { data: Buffer, type: String, required: true }
}
],
recipeName: {
type: String,
required: true
},
created: {
type: Date,
required: true
},
ingredient: {
type: String,
required: true
},
rating: {
type: String
},
steps: [
{
step: { type: String },
picture: { type: String }
}
],
comments: [
{
comment: { type: String },
reply: { type: String }
}
],
pictures: [
{
picture: { data: Buffer, type: String, required: true }
}
]
})
let Recipe = (module.exports = mongoose.model('Recipe', RecipeSchema))
我的發布方法和multer的設置如下所示。
const multer = require('multer')
const storage = multer.diskStorage({
destination: './route/uploads',
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage: storage,
limits: { fileSize: 1000000 },
fileFilter: function(req, file, cb) {
checkFileType(file, cb)
}
})
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/
const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimetype = filetypes.test(file.mimetype)
if (mimetype && extname) {
return cb(null, true)
} else {
cb('Error: Images Only!')
}
}
router.post('/', upload.array('files', 10), (req, res) => {
let files = req.files
var recipe = new Recipe()
for (const key in files) {
if (files.hasOwnProperty(key)) {
console.log(files[key].path)
const fl = fs.readFileSync(files[key].path)
recipe.pictures.picture.data = fl
recipe.pictures.picture.type = 'image/png' // or 'image/png'
}
}
recipe.save()
})
我得到這個錯誤
TypeError:無法設置未定義的屬性“數據”
即使已保存圖片,但是當我嘗試將路徑保存在緩沖區中時,它也不允許我使用。 關於貓鼬,目前尚不清楚如何啟動緩沖區的文檔。
不要將圖像(或文件)保存到數據庫,只需保存圖像名稱即可。
修補程序,但不推薦。
pictures
是一個數組。
for (const key in files) {
if (files.hasOwnProperty(key)) {
console.log(files[key].path)
const fl = fs.readFileSync(files[key].path)
recipe.pictures.push({
picture: {
data: fl,
type: 'image/png'
}
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.