When I use Monk's addToSet
in my route /upload-ajax
, the array just rewrites itself with the first new element.
Here is my code:
const express = require('express');
const router = express.Router();
const debug = require('debug')('hackit:images');
const boom = require('boom');
const fs = require('fs');
const path = require('path');
const config = require('../../config');
const db = require('monk')(config.mdbConnect);
const DBposts = db.get('posts');
const multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname+'/../../public/images/posts/unused')
},
filename: function (req, file, cb) {
let ext = path.extname('index.html')
if(ext!==".png"||ext===".jpg"||ext===".bmp"||ext===".gif") ext = ".jpg"
let filename = new Date().getTime()
cb(null, filename+ext)
}
})
const upload = multer({ storage: storage })
router.get('/pick-:folder', (req, res, next) => {
debug('folder -> '+req.params.folder)
const folder = __dirname+'/../../public/images/posts/'+req.params.folder
fs.readdir(folder, (err, files) => {
if(err) next(boom.resourceGone(err))
files = files.map(x => x = "/images/posts/"+req.params.folder+"/"+x)
res.send(files)
})
})
router.post('/upload-ajax', upload.single('newimg'), (req, res, next) => {
debug('upload-ajax')
debug(req.body)
debug(req.file)
if(!req.file){
res.redirect('back')
}else{
const _id = req.body.id;
let query;
if(req.body.type==="main"){
query = {$set: {postimage: "/images/posts/unused/"+req.file.filename}}
}else{
query = {$addToSet: {images: "/images/posts/unused/"+req.file.filename}}
}
debug(query)
DBposts.findOneAndUpdate({_id}, query, (err, result) => {
if(err) next(boom.badImplementation(err))
req.flash('success', 'Изображение добавлено в статью');
res.location('/admin/posts/edit-'+_id);
res.redirect('/admin/posts/edit-'+_id);
})
}
})
module.exports = router;
What am I doing wrong?
Monks doing all well. As all did. I just didnt save last result into view field.
Error was:
images
param was rewrited as empty.addToSet
and result was writed to empty images
And did it many times. Sorry all for this confusion that i maked.