1

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 ?

EDIT : I forget to add
mongoose.connect("mongodb://localhost:27017/db_ldap_users"); I was thinking the connection to the Database was enough Thanks

Thanks you

1

1 Answer 1

2

look this:

     var mongoose = require('mongoose');


        mongoose.connect("mongodb://localhost:27017/db_ldap_users");

       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");
        });
   });
Sign up to request clarification or add additional context in comments.

2 Comments

can you please add more explanation on this, so that user can understand it more properly?
Ok this is working the mistake was I didn't do mongoose.connect("mongodb://localhost:27017/db_ldap_users"); Thanks you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.