0

In my node app, I have server.js as follows:

// modules =================================================
var express        = require('express');
var app            = express();
var mongoose       = require('mongoose');
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');

// configuration ===========================================
var mongoDB = 'mongodb://root:root@localhost:27017/dms';
mongoose.connect(mongoDB);

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));


db.once('open', function () {
    var tasksSchema = new mongoose.Schema({
        What: String,
        Who: String,
        When: Date
    });
    var Tasks = db.model('Tasks', tasksSchema);
    Tasks.find({}, function (err, tasks) {
        if (err) {
            onErr(err, callback);
        } else {
            mongoose.connection.close();
            console.log(tasks);
            //callback("", tasks);
        }
    });
});

var port = process.env.PORT || 9080; // set our port
// mongoose.connect(db.url); // connect to our mongoDB database (commented out after you enter in your own credentials)

// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded

app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users

// routes ==================================================
require('./app/routes')(app); // pass our application into our routes

// start app ===============================================
app.listen(port);
console.log('Magic happens on port ' + port);           // shoutout to the user
exports = module.exports = app;                         // expose app

When this app starts up, this line of code: console.log(tasks); produces an empty array: []:

/usr/local/bin/node --debug-brk=49753 --nolazy server.js
Debugger listening on port 49753
`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Magic happens on port 9080
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
[]

The same query, when run from mongodb command line, produces a single document:

Eugenes-MacBook-Pro-2:~ eugene$ mongo dms -u "root" -p "root"
MongoDB shell version: 3.0.4
connecting to: dms
> db.Tasks.find()
{ "_id" : ObjectId("59712d3f65283137a1676345"), "What" : "what-1", "Who" : "who-1", "When" : ISODate("2014-01-16T00:00:00Z") }
> 

What can I change in the node / mongoose code, to have it output the same document?

Eugene Goldberg
  • 14,286
  • 20
  • 94
  • 167
  • `var Tasks = db.model('Tasks', tasksSchema, 'Tasks');`. Mongoose has a "default" where the collection name used in the "lowercase" and "plural" form of the model name provided. If you want a specific collection name ( and because you already created the collection ) then you use the "third" parameter to name the collection to use. – Neil Lunn Jul 21 '17 at 00:28
  • That fixes the problem here. But on a broader note, you are using deprecated methods as evidenced by the warnings. You also don't seem to fully grasp the "database connection" concept, as these are things you **never hang up** for something like a http server as you are working on. Also MongoDB 3.0.4?? Getting kind of old now. So I suggest updating that. And update your nodejs and learn Promises& async/await syntax and you will find things much cleaner. – Neil Lunn Jul 21 '17 at 00:31
  • all good points - thanks! – Eugene Goldberg Jul 21 '17 at 00:39

0 Answers0