【大雾】mongoose中createConnection和connect的大坑!
来源:互联网 发布:xboxone手柄映射软件 编辑:程序博客网 时间:2024/05/16 17:00
遭遇此坑真是刻骨铭心。。。。。几乎找了半天的错误。。。查了API,看了好多人的代码。。。最后。。。终于发现是哪里有问题。。。
其实不记得这种写法怎么来的了。。。。= = 因为刚开始看代码的时候会点开很多教程看。。可能默默就错了。。。。
错误:
<span style="font-size:14px;color:#333333;">var db = mongoose.createConnection(setting.host, setting.db);db.once('open',function(){console.log('success');var schema = mongoose.Schema({title:String});var model = mongoose.model('all',schema);var kit = new model({title: 'xxx'});kit.save(function(err, date, num){console.log('!');if(err) console.log(err);else if(date) console.log(date);else console.log(num);})})</span>
现象:可以显示success,但是用save的时候却没有反应。。因为model是错的。。具体反应应该是要追溯到源码的。。。
正确:
在多方求问之后。。。(期间整个人是混乱的。。),有人甩给了我一个API的网址。。我说我一直在看API啊。。然后还是点进去看了下。。上面是connect的正确使用方法。。。于是我想。。这我知道啊!但是我的写法为什么错呢!。。然后灵光乍现!可能本来就不能这么用啊!虽然可以success,但是save的时候回出错啊!然后几分钟这个问题就解决了。。
<span style="font-size:14px;color:#333333;">var db = mongoose.createConnection(setting.host, setting.db);db.once('open',function(){console.log('success');var schema = mongoose.Schema({title:String});var model = db.model('all',schema);var kit = new model({title: 'Fuck'});kit.save(function(err, date, num){console.log('!');if(err) console.log(err);else if(date) console.log(date);else console.log(num);})})</span>
或者是:
<span style="font-size:14px;color:#333333;">mongoose.connect('mongodb://localhost/natsu');var db = mongoose.connection;db.once('open',function(){console.log('success');var schema = mongoose.Schema({title:String});var model = mongoose.model('all',schema);var kit = new model({title: 'Fuck'});kit.save(function(err, date, num){console.log('!');if(err) console.log(err);else if(date) console.log(date);else console.log(num);})})</span>
其实改变就是用create的时候,model的创建不能是mongoose,而应该是db,但是用connect的时候,就要用mongoose.....
文档中是说createConnection更适用于连接多个数据库的情况,connect是用mongoose的default connect......
这方面文档上面没有查到是怎么回事。。。TAT。。我整个人是懵逼的。。。。
其实最有感触的是debug的能力。。还是不够啊。。。。不能明确的描述问题和定位错误。刚开始发现错的时候,我认为是create和connect返回的对象不一样,确实应该是不一样的,查了文档之后朦朦胧胧的。。。(英语太差TAT)
在createConnection下有这么一段话:『This connection object can then be used for creating and retrieving models that are scoped only to this specific connection.』
之前没有发现。。但是现在看起来。。是表示创建model的时候应该要用这个返回的对象
- 【大雾】mongoose中createConnection和connect的大坑!
- mongoose中connect()、createConnection()和connection的区别和作用
- 【大雾】关于mongoose的model的小问题
- 大雾
- Android开发中遇到的大坑
- C语言中字符串的大坑
- solaris移植到linux的大坑:bash和sh中环境变量继承的差异
- iOS数组和字典的使用----大坑
- bindValue 和 bindParam的惊天大坑!
- mongoose使用中遇到的问题一:
- mongoose中通过-id查询的方法
- 讨厌的大雾,讨厌的感冒
- android createConnection
- zeit/micro connect with Mongo by Mongoose
- php中常见的大坑,开发中应尽量避免
- Yii框架中使用Fixtures的一个大坑。。
- IE6 中 window.open() 函数的超级大坑
- Android 中与 so 有关的一个大坑
- 的符合当时法国的帅哥哥和第三方
- 存储器的保护(三)——《x86汇编语言:从实模式到保护模式》读书笔记20
- Centos下mysql允许远程连接后本地登陆失败问题(已解决)
- 商业研究(5):宠物服务市场-概览
- 黄河殇
- 【大雾】mongoose中createConnection和connect的大坑!
- 第3周项目4 年龄几何
- React-Native 自述
- 树回归预测
- 自我反思
- 1054. 求平均值 (20)
- C++第一次上机实验-1-2
- 分享一個鏈接
- OpenGL编程(五)绘直线以及分析绘直线的算法