15

I am bit confused with usage of models in mongoosejs

Models can be created using mongoose in these ways

Using Mongoose

var mongoose = require('mongoose');
var Actor = mongoose.model('Actor', new Schema({ name: String }));

Using Connection

var mongoose = require('mongoose');
var db = mongoose.createConnection(..);
db.model('Venue', new Schema(..));
var Ticket = db.model('Ticket', new Schema(..));
var Venue = db.model('Venue');

Using existing Model instance

var doc = new Tank;
doc.model('User').findById(id, callback);

Now what is the difference between model returned by Mongoose.model , Connection.model and Model.model. and when to use what , what is the recommended way to create/fetch model ?

4

3 回答 3

21
  1. mongoose.model将定义的模型与调用创建的默认连接联系起来mongoose.connect
  2. db.model将模型与调用创建的连接联系起来var db = mongoose.createConnection
  3. doc.modeldoc使用模型所绑定的连接按名称查找另一个模型。

这三个都可以在同一个程序中合理地使用;使用哪一个取决于具体情况。

于 2012-10-09T19:33:30.670 回答
15

好的,这就是我发现的

重要的!如果您使用 mongoose.createConnection() 打开了单独的连接,但尝试通过 mongoose.model('ModelName') 访问模型,它将无法按预期工作,因为它没有连接到活动的数据库连接。在这种情况下,通过您创建的连接访问您的模型:

var conn = mongoose.createConnection('your connection string');
var MyModel = conn.model('ModelName', schema);
var m = new MyModel;
m.save() // works

对比

var conn = mongoose.createConnection('your connection string');
var MyModel = mongoose.model('ModelName', schema);
var m = new MyModel;
m.save() // does not work b/c the default connection object was never connected
于 2012-10-13T23:36:19.993 回答
0

mongoose.connect 是为你连接到同一个数据库,虽然你的数据库是 balance 或 replicaSet

db.model 用于向 Mongo 打开的多个连接,每个连接具有不同的读/写设置

于 2016-05-02T02:46:03.797 回答