Tuesday 22 November 2016

Help! I can't save to Mongo using Mongoose and Express for some reason..

So this is working but not writing to the db. When I restart the server the data just resets. Here's the code in my server.js file: var express = require('express'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var bodyParser = require('body-parser'); var app = express();mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost:27017/food'); //Allow all requests from all domains & localhost app.all('/*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "POST, GET"); next(); }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); var usersSchema = new Schema({ _id: String, id: String, vote: Number }); var bkyes = mongoose.model('bkyes', usersSchema); app.post('/bkyes', function(req, res, next) { bkyes.find({}, function(err, foundObject) { console.log(foundObject); //Print pre-update var found = foundObject[0]; found.vote = req.body.vote; found.save(function(err) { console.log(foundObject); //Print post-update }); }); }); app.listen(3000); /* The console.log pre-update: [ { _id: '582b2da0b983b79b61da3f9c', id: 'Burger King', vote: -1 } ] The console.log post-update: [ { _id: '582b2da0b983b79b61da3f9c', id: 'Burger King', vote: 5 } ] However this data does NOT write to mongo!! */

Submitted November 23, 2016 at 03:37AM by joWebDev

No comments:

Post a Comment