Sunday, 2 April 2017

Node.JS - Mongoose won't save data to MongoDB and Object not getting information correctly?

So firstly, I checked the relevant question but since I'm not using the same middleware, I don't think it helped me. I have a regular form and while it successfully goes through req.body and I can print all the form values. However the problems are when I try to create a new object because when I print it, it doesn't have the correct fields that I assigned it...? And secondly, when I try to save it, it doesn't show up in the Db when I check via Terminal. I have successfully run Mongod and am connected to the correct Db and collection so I'm confused. Any help would be greatly appreciated!

Here is the relevant code

App.js:

    var express = require('express');
var app = express();
var db = require('./db.js');
var path = require('path');

var bodyParser = require('body-parser');
var handlebars = require('hbs');

var mongoose = require('mongoose');
var museumObj = mongoose.model('MuseumObject');

//For Images
var fs = require('fs');
var multer = require('multer');
//Saves to memory storage 
var upload = multer({ storage: multer.memoryStorage({}) });

//Port setting
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function(req, res) {
    res.render('index');
});

app.get('/AdvancedSearch', function(req, res) {
    res.render('AdvancedSearch');
});

app.get('/AskUs', function(req, res) {
    res.render('AskUs');
});

app.get('/Themes', function(req, res) {
    res.render('Themes');
});

app.get('/AddObj',  function(req, res) {
    res.render('AddObj');
});

app.post('/AddObj',upload.single('pic'),function(req,res){
    console.log("here is the req.body");
    console.log(req.body);
    var base64 = req.file.buffer.toString('base64');

    var dim='';
    if(req.body.length && req.body.width && req.body.height){
        dim = req.body.req.body.length +" x "+req.body.width+" x "+req.body.height
    }

    var newObj = new museumObj({
        accessionNum: req.body.accession,
        maker: req.body.maker,
        manufacturer: req.body.manufacturer,
        title: req.body.title,
        date: req.body.date,
        medium: req.body.medium,
        dimesions: dim,
        marks: req.body.marks,
        description: req.body.description,
        pic: base64,
    });
    console.log('here is the new object before calling the save function');
    console.log(newObj);
    newObj.save(function(err,item, count){
        if (err){
            console.log("there is an error");
            console.log(err);
        }
        else{
            console.log('here is the "successfully" saved item');
            console.log(item);
            //res.redirect('/');
        }
    });

});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

Db.js:

var mongoose = require('mongoose');
var URLSlugs = require('mongoose-url-slugs');


var MuseumObject = new mongoose.Schema({
  accessionNum: String,
  maker: {String, default: ''},
  manufacturer: {String, default: ''},
  title: String,  
  date: {String, default: ''},
  medium: {String, default: ''}, 
  dimensions: {String, default: ''},
  marks: {String, default: ''},
  description: {String, default: ''},
  pic: {String, default: ''}
});


MuseumObject.plugin(URLSlugs('title'));
mongoose.model('MuseumObject', MuseumObject);

// is the environment variable, NODE_ENV, set to PRODUCTION? 
if (process.env.NODE_ENV == 'PRODUCTION') {
  console.log("in production");
 // if we're in PRODUCTION mode, then read the configration from a file
 // use blocking file io to do this...
 var fs = require('fs');
 var path = require('path');
 var fn = path.join(__dirname, 'config.json');
 var data = fs.readFileSync(fn);

 // our configuration file will be in json, so parse it and set the
 // conenction string appropriately!
 var conf = JSON.parse(data);
 var dbconf = conf.dbconf;
} 
else {
 // if we're not in PRODUCTION mode, then use
 dbconf = 'mongodb://localhost/BKMuseum';
}

mongoose.connect(dbconf);

HTML File:

<h1>Add an Object to the Collection<h1>

<h3>

 <form method="POST" action="AddObj" id="AddObj" enctype='multipart/form-data'>
        *Accession #:  <input type="text" name = "accession" value ="" required>
        <BR>
        Maker/Designer/Artist: <input type="text" name = "maker" value ="">
        <BR>
        Manufacturer: <input type="text" name = "manufacturer" value ="" >
        <BR>
        *Title: <input type="text" name = "title" value ="" required >
        <BR>
        
        *Date : <input type="text" name="date" value="" required>
        <BR>
        *Medium: <input type="text" name="medium" value="" required>
        <BR>
        <div>
            Dimensions:
            <blockquote>
                <input type="number" name="length" form="AddObj"> X <input type="number" name="width" form="AddObj"> X <input type="number" name="height" form="AddObj">
            </blockquote>
        </div> 
        Marks: <input type="text" name="marks" value="">
        <div> Description
                <BR>
                <textarea name="description" form="AddObj" cols='50' style="resize:none; font-size:16px;"></textarea>
        </div>
        <br>
        <div>
            Image Upload
            <BR>
            <input type="file" name="pic" accept="image/*" form="AddObj" required>
        </div>
        <br>
        <input type="submit" value="Submit" form="AddObj">
    </form>

</3>
    <p>
        <a href="/">Go Back to Research Center's Home Page </a href>
    </p>

Here is the relevant outputs
Console output
- Mongo console output:

use BKMuseum
switched to db BKMuseum
db.BKMuseum.count()
0
db.BKMuseum.find({})



via Ms.Aquaberry

No comments:

Post a Comment