Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose not recognizing the collection by name [duplicate]

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

like image 585
Chum-Chum Scarecrows Avatar asked Nov 26 '25 20:11

Chum-Chum Scarecrows


1 Answers

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);
like image 56
hassansin Avatar answered Nov 29 '25 08:11

hassansin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!