node.js - 如何用nodejs和mongoose查找文档,为什么没有结果?

标签 node.js mongodb mongoose

person集合中有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

最佳答案

问题在于,当您使用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' ]

关于node.js - 如何用nodejs和mongoose查找文档,为什么没有结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886736/

相关文章:

node.js - Mongoose find() 具有多个条件

mongodb - 如何连接/查询 Mongoose 到现有数据库

node.js - Mongoose 填充不填充数组

javascript - 全局安装后找不到模块 'socket.io'

node.js - Windows 7 上的 Nginx 并检测 Node.js

node.js - Mongoose 更新只更新第一个文件

node.js - Node-webshot - 图像未在服务器上生成,但相同的代码在本地生成图像

mongodb - 为什么 serverstatus 对 mongod 写操作有不好的影响?

mongodb - Docker 容器无法绑定(bind)到网络

Node.js 无法使用 mongoose 设置默认 UUID