3

Here's my code:

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'mcfly');

db.once('open', function() {

    var schema = new mongoose.Schema({
        firstname: String,
        lastname: String
    });

    var col = db.model('mathpeep', schema);

    col.find({firstname: 'hey'}, function(err, Col) {
        console.log(Col);
    });
})

I have mongod running properly, and I ran "mango" and inputted a couple entries to the database "mcfly" inside the collection "mathpeep". This code is basically copied from another place where it works, down to variable names, so I have no clue what's wrong.

The problem is that my db looks like this:

> use mcfly
switched to db mcfly
> db.createCollection('mathpeep')
{ "ok" : 1 }
> show collections
mathpeep
system.indexes
> db.mathpeep.insert({firstname: 'hey', lastname: 'ayy'})
WriteResult({ "nInserted" : 1 })
> db.mathpeep.insert({firstname: 'aaa', lastname: 'aaaaa'})
WriteResult({ "nInserted" : 1 })
> db.mathpeep.find()
{ "_id" : ObjectId("5592e96566cf1404577ebe1b"), "firstname" : "hey", "lastname" : "ayy" }
{ "_id" : ObjectId("5592e97b66cf1404577ebe1c"), "firstname" : "aaa", "lastname" : "aaaaa" }
> 

Yet the code above returns an empty file (?). The same happens when I try saving a file using that schema: the script finishes without problem, but when I check the database using the shell, nothing was saved. I'm copying the code from somewhere else, that saves and reads from the database just fine. I also ran the mongoose install again, if it did not install correctly then I have no clue how to fix it.

There are no errors: When I run the script, it prints this:

[]

And that's all that happens.

I can only assume I'm connecting somewhere else or something, hence the question name.

Thanks

2 Answers2

8

I think it's because mongoose adds an s to make it plural. So it's checking in the collection mathpeeps. To explicitly tell the collection name use third argument:

var col = db.model('mathpeep', schema, 'mathpeep');

To make sure what's the query it's making add this in you code:

mongoose.set('debug', true);
hassansin
  • 16,918
  • 3
  • 43
  • 49
1

Try connecting like this:

var db = mongoose.createConnection('mongodb://localhost:27017/mcfly');

And access your collection like this:

var col = mongoose.model('mathpeep', new Schema({ firstname: String, lastname: String }), 'mathpeep' ) //here goes your collection name;

Leo
  • 449
  • 2
  • 17