tairyao
tairyao

Reputation: 145

How to find documents with nodejs and mongoose, why there is no result?

There is 3 documents in person collection, but I can't find()

mongodb shell:

> use test;
switched to db test
> db.person.find();
{ "_id" : ObjectId("527f18f7d0ec1e35065763e4"), "name" : "aaa", "sex" : "man", "height" : 180 }
{ "_id" : ObjectId("527f1903d0ec1e35065763e5"), "name" : "bbb", "sex" : "man", "height" : 160 }
{ "_id" : ObjectId("527f190bd0ec1e35065763e6"), "name" : "ccc", "sex" : "woman", "height" : 160 }

my nodejs code:

var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://uuu:ppp@localhost:27017/test');
//mongoose.set('debug', true);

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
    console.log("connection success!");
    mongoose.model('person', mongoose.Schema({ name: String}),'person');

    var out = db.model('person');
    //console.log(out);
    out.find({},function(err, obj) {
        console.log(obj);
        console.log(1);
    });
});

But, the result is : connection success! [] 1

Upvotes: 2

Views: 4741

Answers (2)

robertklep
robertklep

Reputation: 203231

The issue is that when you use createConnection, you need to use the .model method of the created connection, instead of mongoose.model:

var db = mongoose.createConnection(...);

// wrong:
mongoose.model('person', mongoose.Schema({ name: String}),'person');

// right:
db.model('person', mongoose.Schema({ name: String}),'person');

// perform query:
db.model('person').find(...);

The reason is that, as far as I understand, a model is 'associated' to a connection. When you use mongoose.model, the model is associated to the default connection, but you're not using that (you're using a connection that you create explicitly with createConnection).

Another way to show this is using modelNames:

// wrong:
mongoose.model('person', mongoose.Schema({ name: String}),'person');
console.log('default conn models:', mongoose.modelNames()); // -> [ 'person' ]
console.log('custom  conn models:', db.modelNames());       // -> []

// right:
db.model('person', mongoose.Schema({ name: String}),'person');
console.log('default conn models:', mongoose.modelNames()); // -> []
console.log('custom  conn models:', db.modelNames());       // -> [ 'person' ]

Upvotes: 3

Salvador Dali
Salvador Dali

Reputation: 222461

The problem is that you are not putting your find statement inside the callback for connection.

Try to put it here:

db.once('open', function callback () {
    console.log("connection success!");

    mongoose.model('person', mongoose.Schema({ name: String}), 'person');

    db.model('person').find({name:'aaa'},function(err, obj) {
      console.log(obj);
    });
});

Upvotes: 0

Related Questions