Wednesday, 5 April 2017

mongoDB / NodeJS save() method not working

I'm a beginner at NodeJS / MongoDB so maybe it would be easy for you.

I have this simple code :

var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird')

MongoClient.connect("mongodb://localhost:27017/db_ldap_users", function(err, db) {
    if(err) {
       throw err;
    }
    console.log("connected to the mongoDB !");
});

var usersSchema = new mongoose.Schema({uid : String });

var Users = mongoose.model('Users', usersSchema);

app.get("/test", function(req, res) {
    console.log("Service /test called");
    var users = new Users();
    users.uid = "James";
    console.log("User created");

    users.save(function(err) {
        console.log("Callback");
        if (err) { 
            console.log("error");
            throw err; 
        }
        console.log('added !');
        res.send("ok");
    });
});

Here is the output :

connected to the mongoDB !
Service /test called
User created

The problem is the user is never add to the DB. I have never entered in the callback, I don't know why, I have followed multiple tutorial and it seems to always works for them. Does someone has an idea ?

Thanks you



via Foushi

No comments:

Post a Comment