Nodejs mongoose.createConnection()和mongoose.connect()区别

Nodejs mongoose.createConnection()和mongoose.connect()区别

这里不是很明白为什么2个的名字要如此相同,新手都有点糊涂。查了一些文档,当require(‘mongoose’)时,就相当于 mongoose.createConnection(),而如果新手用这个mongoose.model,往往是不成功的。因为永远不会连接。

我也是最近在用这个,欢迎大家讨论,有很多不懂的。

两种方式对比:

var mongoose = require('mongoose');

db = mongoose.createConnection(‘localhost’, ‘test’); var schema = new mongoose.Schema({ name: String }); var collectionName = ‘kittens’; var M = db.model(‘Kitten’, schema, collectionName); var silence = new M({ name: “Silence”}); silence.save(function(err){

});

var mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/test’);
db = mongoose.connection;
db.once(‘open’, function callback () {
// yay!
});	
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model(‘kitten’, kittySchema);
var silence = new Kitten({ name: “Silence”});
silence.save(function(err){

});


14 回复

Node.js Mongoose.createConnection() 和 mongoose.connect() 区别

在使用 Mongoose 进行数据库操作时,mongoose.createConnection()mongoose.connect() 是两个常用的方法,但它们的功能和使用场景有所不同。

mongoose.connect()

mongoose.connect() 是一个全局方法,它会创建一个新的默认连接,并返回一个 Promise。这个方法通常用于应用只有一个数据库连接的情况。

var mongoose = require('mongoose');

// 使用 mongoose.connect()
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });

var kittySchema = mongoose.Schema({
  name: String
});

var Kitten = mongoose.model('kitten', kittySchema);

var silence = new Kitten({ name: "Silence" });
silence.save(function (err) {
  if (err) throw err;
  console.log('Kitten saved!');
});

在这个例子中,我们通过 mongoose.connect() 创建了一个到 MongoDB 的连接。一旦连接成功,就可以定义模型并进行数据操作。

mongoose.createConnection()

mongoose.createConnection() 则允许你创建多个独立的数据库连接。这对于需要同时连接到多个数据库的应用非常有用。

var mongoose = require('mongoose');

// 使用 mongoose.createConnection()
var db = mongoose.createConnection('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });

var schema = new mongoose.Schema({ name: String });
var collectionName = 'kittens';

var M = db.model('Kitten', schema, collectionName);

var silence = new M({ name: "Silence" });
silence.save(function (err) {
  if (err) throw err;
  console.log('Kitten saved!');
});

在这个例子中,我们通过 mongoose.createConnection() 创建了一个新的数据库连接。然后在这个连接上定义模型并进行数据操作。

总结

  • mongoose.connect() 用于创建全局的默认连接,适用于只有一个数据库连接的应用。
  • mongoose.createConnection() 允许创建多个独立的数据库连接,适用于需要连接到多个数据库的应用。

希望这些示例代码能帮助你更好地理解两者的区别。如果你有任何疑问,欢迎继续讨论!


你看的怎么样了,我就栽倒这里了,createConnection,虽然可以open,但完全不会查询。修改成第二种方法,就OK了,搞死了,好几个小时浪费了…

我也好晕啊,还有我的密码里包含@符号咋整啊

require('mongoose')返回的是一个Mongoose实例 每个Connection对应一个数据库,由Connection#model定义这个数据库的Model 每个Mongoose实例可以连接多个Connection,这些Connection共用由Mongoose#model定义的Model

感谢这个问题,让我把一直模糊的的知识弄清了

这个东西自己写一个就行了,需要什么模块。

参考核心模块http - request + ClientRequest 或者 net - connect + Socket

还是不清楚这两者的意义在哪里

同样的情况用createConnection,完全操作不了数据库。改用connection就正常

### Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`.

Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`.

```js
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/my_database');

Once connected, the open event is fired on the Connection instance. If you’re using mongoose.connect, the Connection is mongoose.connection. Otherwise, mongoose.createConnection return value is a Connection.

Important! Mongoose buffers all the commands until it’s connected to the database. This means that you don’t have to wait until it connects to MongoDB in order to define models, run queries, etc.

Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use mongoose.connect. If you need to create additional connections, use mongoose.createConnection.

Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.

var mongoose = require('mongoose');

mongoose.connect(‘mongodb://localhost/my_database’);

Once connected, the open event is fired on the Connection instance. If you’re using mongoose.connect, the Connection is mongoose.connection. Otherwise, mongoose.createConnection return value is a Connection.

Important! Mongoose buffers all the commands until it’s connected to the database. This means that you don’t have to wait until it connects to MongoDB in order to define models, run queries, etc.

学习学习

怎样定义 db 才可以使用类似 db.user.find({}) 这样查询方式呢?

http://stackoverflow.com/questions/22786374/queries-hang-when-using-mongoose-createconnection-vs-mongoose-connect 这个有比较详细的介绍。如果使用mongoose.connect的话,它连接的是default connection;而如果是db = mongoose.createConnection(xxxx)的话,因为它返回的是一个connection,所以接下来再进行model生成的时候需要使用 db.model 而不是 mongoose.model

mongoose.createConnection()mongoose.connect() 都是用来连接 MongoDB 的方法,但它们之间有一些关键的区别。

区别

  1. 单个 vs 多个数据库连接

    • mongoose.connect():默认情况下,它会创建一个单一的全局连接,并可以用来定义多个模型。
    • mongoose.createConnection():用于创建单独的数据库连接实例,适用于需要连接多个不同数据库的情况。
  2. 使用场景

    • 如果你需要管理多个数据库连接,建议使用 mongoose.createConnection()
    • 如果只需要一个数据库连接,使用 mongoose.connect() 更为简便。
  3. 返回值

    • mongoose.connect() 返回一个 Promise 对象。
    • mongoose.createConnection() 返回一个 Connection 实例,该实例可以用来定义模型。

示例代码

使用 mongoose.createConnection()

var mongoose = require('mongoose');

// 创建一个新的数据库连接
var db = mongoose.createConnection('mongodb://localhost/test');

// 定义 Schema 和 Model
var schema = new mongoose.Schema({ name: String });
var CollectionName = db.model('Kitten', schema);

var kitten = new CollectionName({ name: "Silence" });
kitten.save(function(err) {
    if (err) console.error(err);
    console.log("Saved successfully!");
});

使用 mongoose.connect()

var mongoose = require('mongoose');

// 连接到数据库
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });

// 获取连接实例
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
    console.log("Connected to MongoDB!");

    // 定义 Schema 和 Model
    var schema = new mongoose.Schema({ name: String });
    var Kitten = mongoose.model('Kitten', schema);

    var kitten = new Kitten({ name: "Silence" });
    kitten.save(function(err) {
        if (err) console.error(err);
        console.log("Saved successfully!");
    });
});

总结

  • 如果你只需要一个数据库连接,推荐使用 mongoose.connect()
  • 如果你需要多个数据库连接,应该使用 mongoose.createConnection()

希望这能帮助你更好地理解这两个方法之间的差异。

回到顶部