Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign up60.[半夜改bug] mongoose 的 createConnection 和 connect #65
Comments
|
这里需要使用连接的返回值定义Model?文档并没有啊,文档是直接是使用mongoose.model定义的 var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
mongoose.Promise = global.Promise;
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('meow');
}
}); |
|
使用默认链接,为什么不在进程初始化的的时候创建链接,然后: // 定义schema
const mongoose = require('mongoose')
const NameSchema = new Schema({
name: String
})
// 如果也在进程初始化的时候加载,此处不用export
mongoose.model('Name', NameSchema);
// curd
const mongoose = require('mongoose')
const NameModel = mongoose.model('Name')
...还有多个数据库的时候为什么不这么导出: module.exports = db; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[半夜改bug] mongoose 的 createConnection 和 connect
因为代码里 mongo 数据库的连接方式的代码被改成了
const db = mongoose.createConnection(mongo.url(), mongoOptions),所以在调用数据插入函数时Promise的 resolve 和 reject 都没有返回,也没有打印任何异常信息。查了业务逻辑、本地 mongo 的读写都没问题,最后发现是 mongo 的连接文件 connect.js 被修改了。
因为用了
mongoose.createConnection所以此时的 model 应该是db.mongoose.model('Product')而之前的是用默认的
mongoose.connect()方式连接的数据库,获取 model 的代码也应该是const ProductModel = db.mongoose.model('Product', ProductSchema)数据库的链接方式被改了,model 没有变,所以增删改查的代码一直被挂起,没有任何的返回。😂 😂 😂
API和示例代码
Mongoose#connect
API
Mongoose#connect开启默认的 mongoose 连接。如果只连接一个库,就用这个默认的。1.连接数据库 mongo.js
Mongoose#createConnection
API里是这样写的
Mongoose#createConnection是适合于多个数据库连接的方式1.连接数据库 mongo.js
最后
要多看 API 文档 。。。。