model.save()让我很困惑。
举例说明。我在单独的model.js文件中移动了我的mongoose.model(mongoose.schema)。当我使用这种方法创建模型时,下面的问题困扰着我。
save方法如何找到我与db建立的连接。秒如果我有2个mondogDB连接实例,它会选择哪一个?
以下是模式
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);发布于 2018-08-03 22:38:44
因此,mongoose.model()的输出是一个模型,并且给定的模型总是绑定到一个连接。
默认情况下,大多数人只使用mongoose.connect()提供的连接和连接池。一旦调用它,缓存的mongoose模块就会在幕后使用一个单例连接对象。举个例子,如果我调用你的模型,我会这样做:
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内部单例,所以我必须使用创建的连接进行操作。例如:
// ./schemas/user.js
// You now export the Schema rather than the module in your file
//module.exports = mongoose.model('User', User);
module.exports = User;然后在调用代码中:
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. https://stackoverflow.com/questions/51674576
复制相似问题