V
V
Valery Orlov2018-11-15 14:26:48
JavaScript
Valery Orlov, 2018-11-15 14:26:48

How to correctly update the field?

When uploading files, an out-of-sequence occurs, causing the file name to not update correctly and the collection field filenameto remain empty.

const router = require('express').Router();
const mongoose = require("mongoose");
const multer = require('multer');
const aws = require('aws-sdk');
const multerS3 = require('multer-s3');
const Collection = require("../models/ts");

aws.config.update({
    secretAccessKey: process.env.ACCESS_KEY,
    accessKeyId: process.env.ACCESS_KEY_ID,
    region: process.env.REGION
});

const s3 = new aws.S3();
const upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'site.com',
        acl: 'public-read',
        key: function (req, file, cb) {
          cb(null, path);
          
           Collection.update({ vid: req.body.vid }, { $set: {
            filename: file.originalname,
            } })
      .exec()
      .then(result => {
        console.log('Название файла успешно сохранено');
        })
      .catch(err => {
        console.log(err);
      });
          }
      })
}).any();

router.post("/", upload,(req, res, next) => {
switch(req.body.cs) {

case "addCollection":
 
  const ts = new Collection({
   _id: new mongoose.Types.ObjectId(),
   vid: req.body.vid,	
   filename: ''
  });
  
  ts.save()
  .then(result => {
    if(result){
    console.log('Данные успешно записан в коллекцию');
  } else {
    console.log('Данные в коллекцию не записаны');
  }
  })
  .catch(err => {
        console.log('Ошибка записи в коллекцию');
    });

  res.status(200).json({
    "result":"ok",
  });
  break;

case "addFilename":
  upload(req, res, function (err) {

      if(err) {
        console.log('Ошибка загрузки файлов');
        res.status(500).json({
          Error: "Ошибка загрузки файлов"
        });
        }

        res.status(200).json({
          "result":"ok",
        });
      });
  break;
}
});

In a nutshell, in addCollection the fields are saved, with the filename field still empty, and in addFilename we already get the file itself and update filename with its name.
As a result of the code above, we get the following in the console:
Название файла успешно сохранено
Данные успешно записан в коллекцию

It follows that the update of the filename field occurs before the entry itself actually appears in the collection.
Please help me handle this situation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Chernyshev, 2018-11-16
@IvanBlacky

Here is your code that reports that an entry has been added to the collection:

res.status(200).json({
    "result":"ok",
  });
  break;

However, this message is false, because this code is not called in the chain of the promise to add the file. Accordingly, you need to write like this:
ts.save()
  .then(result => {
    if(result){
    console.log('Данные успешно записан в коллекцию');
      res.status(200).json({
        "result":"ok",
       });
  } else {
    console.log('Данные в коллекцию не записаны');
  }
  })
  .catch(err => {
        console.log('Ошибка записи в коллекцию');
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question