mongodbexpressmonk

Monk addToSet rewrites array


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?


Solution

  • Monks doing all well. As all did. I just didnt save last result into view field.

    Error was:

    1. I select new image
    2. Before updating images array, I maked presave all fields in form. And images field was empty. Thats why presaved form images param was rewrited as empty.
    3. Next I updated my images with addToSet and result was writed to empty images
    4. Next I reloaded post edit page, and thought that have no errors in my code.

    And did it many times. Sorry all for this confusion that i maked.