jdev99 jdev99 - 15 days ago 7
Node.js Question

My local MongoDB instance is not saving data via Express and Mongoose

So this is working in the console but not writing to the db. When I restart the server the data just resets. It's reading from the db just fine, just not saving. I'm running the mongo shell and clearly pulling data from it, just not updating or creating data like I want. 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; //Passing in the number 5 here(was -1 before)
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 the db and just resets when you restart the server!!
*/

Answer

The foundObjectsis not effect by save() function in anyway, so the logs is kind of useless.

I don't know why you want to find every documents in bkyes and get the first one out. You often find a document with some conditions, and it is usually the _id field.

Anyway, here is an example with findOneAndUpdate():

bkyes
  .findOneAndUpdate({
    // Conditions
    _id: '00001'
  }, {
    // Set which fields to update
    vote: 5 
  })
  .exec(function(err, foundObject) {
    if (err) {
      // Error handler here
    }

    // Do something when update successfully
  });

NOTES: foundObject is the object before the update.