2

個人コレクションに3つのドキュメントがありますが、見つかりません()

mongodb シェル:

> 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 }

私のnodejsコード:

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);
    });
});

しかし、結果は: 接続成功! [] 1

4

2 に答える 2

3

問題は、 を使用する場合、 ではなく、作成された接続のメソッドcreateConnectionを使用する必要があることです。.modelmongoose.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(...);

その理由は、私が理解している限り、モデルは接続に「関連付けられている」ためです。を使用するmongoose.modelと、モデルは既定の接続に関連付けられますが、それを使用していません (で明示的に作成した接続を使用していますcreateConnection)。

これを示す別の方法は、次を使用すること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' ]
于 2013-11-10T17:14:50.707 に答える
0

問題は、接続のためのコールバック内に find ステートメントを入れていないことです。

ここに置いてみてください:

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);
    });
});
于 2013-11-10T06:15:00.627 に答える