Nodejs: validation failed: img: Cast to Buffer failed for value

Viewed 222

I have tried to save the image in mongoose. I have followed this tutorial. My dataSchema is look like below,

const dataSchema = new mongoose.Schema({
  name: {
    type: String,
    required: false,
  },
  img: {
    type: Buffer,
    contentType: String,
    required: false,
  }
});

I have created a separate folder for routers. Here is my routers.js file,

//Define storage for multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads");
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, file.fieldname + "-" + uniqueSuffix);
  },
});
const upload = multer({ storage: storage });

// Post request
router.post("/", upload.single("img"), async (req, res) => {
      const data = new Data({
      name: req.body.name,
      img: {
        data: fs.readFileSync(
          path.join(__dirname, "../uploads/" + req.file.filename)
        ),
        contentType: "image/png",
      },
    });

    await Data.create(data);
    res.send(req.body);
});

I have tried without img field, It was working fine. But with the image field, it is given the following error. I am testing this API in Postman.

(node:476) UnhandledPromiseRejectionWarning: ValidationError: Data validation failed: img: Cast to Buffer failed for value " {
  data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 01 f0 00 00 01 0a 08 02 00 00 00 62 c7 90 ce 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... 22098 more bytes>,
  contentType: 'image/png'
}" (type Object) at path "img"
    at model.Document.invalidate (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\mongoose\lib\document.js:2879:32)
    at model.$set (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\mongoose\lib\document.js:1426:12)    at model.$set (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\mongoose\lib\document.js:1128:16)    at model.Document (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\mongoose\lib\document.js:148:12)
    at model.Model (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\mongoose\lib\model.js:106:12)   
    at new model (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\mongoose\lib\model.js:4752:15)    
    at C:\Users\gic\Downloads\FloodAPI\MEN API\routers\flood.js:51:17
    at Layer.handle [as handle_request] (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\gic\Downloads\FloodAPI\MEN API\node_modules\express\lib\router\route.js:137:13)    
    at Immediate.<anonymous> (C:\Users\gic\Downloads\FloodAPI\node_modules\multer\lib\make-middleware.js:53:37)
(node:476) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection 
id: 1)
(node:476) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

I used Django before. It was very easy to handle the files. Nodejs seems very complicated for me. Any detailed explanation would be highly appreciated. Please help me to solve this issue.

0 Answers
Related