这里不是很明白为什么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){
});
require('mongoose')
返回的是一个Mongoose
实例
每个Connection
对应一个数据库,由Connection#model
定义这个数据库的Model
每个Mongoose
实例可以连接多个Connection
,这些Connection
共用由Mongoose#model
定义的Model
### 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.