当我在路线addToSet
中使用Monk的/upload-ajax
时,数组只会使用第一个新元素重写自己。
这是我的代码:
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;
我做错了什么?
答案 0 :(得分:0)
和尚做得很好。一切都做到了。我只是没有将最后的结果保存到视野中。
错误是:
images
param被重新归为空。addToSet
更新了我的图片,结果被写为空images
并做了很多次。对不起我所造成的这种混乱。