Search code examples
javascriptmongodbmongoosemongoose-schemamongoose-populate

My mongoose collection not saving the passed data on to the database


I created my schema using mongoose but the collection is not saving the passed data onto the database as a matter of fact the collection is on the database list of collection

The model is

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MovieSchema = new Schema({
	description: String,
	category: String,
	token:  String,
	fileID: {
		type: Schema.Types.ObjectId,
	}
});

const Movie = mongoose.model('Movies', MovieSchema);

module.exports = Movie;

while logistic on saving the documents is

router.post('/', upload.single('file'), (req, res) => {
    
      
    const movie = new Movie({
        description: req.body.Description,
        category: req.body.Category,
        token: req.body.Description,
        fileID: req.file.id 
    })
    movie.save(function(err){
      if(err){
           console.log(err);
           return;
      }

      res.json({ "success": "true"});
});
 
});

if i console.log(movie) i can see the objects 

Solution

  • I tried using the same setup as you did:

    • Express
    • Multer
    • Multer GridFS Storage
    • Mongoose

    It seemed to work (got { success: true } response and stuff stored in the db), as this excerpt from a mongo console session shows:

    > db.movies.find();
    { "_id" : ObjectId("5c02a7ccfe06f6644fc891e7"), "fileID" : ObjectId("5c02a7ccfe06f6644fc891d5"), "__v" : 0 }
    > db.fs.files.find();
    { "_id" : ObjectId("5c02a7ccfe06f6644fc891d5"), "length" : 4265368, "chunkSize" : 261120, "uploadDate" : ISODate("2018-12-01T15:25:00.411Z"), "filename" : "d32a3c421f8b7bb1654f2abe13e9cf0f", "md5" : "c6203a2cfee5169a8c90015b99bb7844", "contentType" : "image/jpeg" }
    

    Here are my files.

    Main Express app file

    // index.js
    const express = require('express');
    const mongoose = require('mongoose');
    const moviesRouter = require('./routes/movies');
    
    mongoose.connect('mongodb://localhost:27017/movies');
    
    const app = express();
    
    app.use(express.static('public'));
    app.use('/api/movies', moviesRouter);
    
    app.listen(8000);
    

    Movies model (same as you)

    // models/Movie.js
    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const MovieSchema = new Schema({
        description: String,
        category: String,
        token:  String,
        fileID: {
            type: Schema.Types.ObjectId,
        }
    });
    
    const Movie = mongoose.model('Movies', MovieSchema);
    
    module.exports = Movie;
    

    Movies route (mostly your code too)

    // routes/movies.js
    const express = require('express');
    const multer  = require('multer');
    
    const router = express.Router();
    const Movie = require('../models/Movie');
    
    // Create a storage object with a given configuration
    const storage = require('multer-gridfs-storage')({
      url: 'mongodb://localhost:27017/movies'
    });
    
    // Set multer storage engine to the newly created object
    const upload = multer({ storage: storage });
    
    router.post('/', upload.single('file'), (req, res) => {
    
      const movie = new Movie({
        description: req.body.Description,
        category: req.body.Category,
        token: req.body.Description,
        fileID: req.file.id 
      });
      movie.save(function(err){
        if(err){
          console.log(err);
          return;
        }
    
        res.json({ "success": "true"});
      });
    
    });
    
    module.exports = router;
    

    HTML test page

    Located under public/index.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>StackOverflow mongoose/gridfs question</title>
      </head>
      <body>
        <div id="status"></div>
        <form id="movie" method="POST" enctype="multipart/form-data">
    
          <label for="file">Choose movie</label>
          <input id="file" type="file" name="file" />
    
          <input type="submit" value="Send" />
        </form>
        <script>
          const status = document.getElementById('status');
          const form = document.getElementById('movie');
          const fileInput = document.getElementById('file');
          console.log(fileInput);
          form.addEventListener('submit', event => {
            event.preventDefault();
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
    
            var request = new XMLHttpRequest();
            request.open('POST', '/api/movies');
            request.onload = function(event) {
              if (request.status == 200) {
                status.innerHTML = 'Sent!';
              } else {
                status.innerHTML = `Error: ${request.status}`;
              }
            };
    
            request.send(formData);
          });
        </script>
      </body>
    </html>
    

    Since I do not have your whole code, it's hard to know where the problem lies precisely:

    • Is your mongo database set up ? (with e.g. use movies;)
    • Is it a problem with the way data are encoded when you sent them to the server (you should have multipart/form-data encoding, see screenshot) StackOverflow mongoose/multer gridfs post

    Hope this helps.