如何找到nodejs和mongoose的文件,为什么没有结果?

时间:2013-11-10 05:54:51

标签: node.js mongodb mongoose

个人收藏中有3个文件,但我找不到()

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 }

我的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

2 个答案:

答案 0 :(得分:3)

问题是,当您使用createConnection时,您需要使用已创建连接的.model方法,而不是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(...);

原因是,据我所知,模型与连接“关联”。当您使用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' ]

答案 1 :(得分: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);
    });
});