首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拯救Mongoose

拯救Mongoose
EN

Stack Overflow用户
提问于 2018-08-03 22:14:04
回答 1查看 98关注 0票数 1

model.save()让我很困惑。

举例说明。我在单独的model.js文件中移动了我的mongoose.model(mongoose.schema)。当我使用这种方法创建模型时,下面的问题困扰着我。

save方法如何找到我与db建立的连接。秒如果我有2个mondogDB连接实例,它会选择哪一个?

以下是模式

代码语言:javascript
复制
const Schema = require("mongoose").Schema;
const mongoose = require("mongoose");

   const User = new Schema({
   name: String, 
   password: String, 

   date_created: {
      type: Date,
      default: Date.now
   },

   authorized: {
      type: Boolean,
      default: false
   } 
});

module.exports = mongoose.model("User", User);
EN

回答 1

Stack Overflow用户

发布于 2018-08-03 22:38:44

因此,mongoose.model()的输出是一个模型,并且给定的模型总是绑定到一个连接。

默认情况下,大多数人只使用mongoose.connect()提供的连接和连接池。一旦调用它,缓存的mongoose模块就会在幕后使用一个单例连接对象。举个例子,如果我调用你的模型,我会这样做:

代码语言:javascript
复制
const mongoose = require('mongoose');
const User = require('./models/user');

mongoose.connect(); // or pass in a custom URL

// from here, User will default to the mongoose-internal connection created in the previous line

如果我想使用多个连接,我不能使用mongoose内部单例,所以我必须使用创建的连接进行操作。例如:

代码语言:javascript
复制
// ./schemas/user.js
// You now export the Schema rather than the module in your file
//module.exports = mongoose.model('User', User);
module.exports = User;

然后在调用代码中:

代码语言:javascript
复制
const config = require('./config'); // presumably this has a couple mongo URLs
const mongoose = require('mongoose');
const UserSchema = require('./schemas/user');

const conn1 = mongoose.createConnection(config.url1);
const conn2 = mongoose.createConnection(config.url2);

const User1 = conn1.model('User', UserSchema);
const User2 = conn2.model('User', UserSchema);

// now any users created with User1 will save to the first db, users created with User2 will save to the second. 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51674576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档