gpt4 book ai didi

javascript - 模块参数的 Node js module.exports

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:45 24 4
gpt4 key购买 nike

我是 Node.js 新手,我创建了一个基于 mongoose 的模块,但配置功能有问题。

实际上我的模块使用mongoose.connect连接,但我想更改它以使用mongoose.createConnection。为此,我创建了一个 init 函数,它接受连接字符串作为参数。

我的问题是“如何module.exports将连接连接到我的模块中?”

例如:

// server.js
var mymodule = require('mymodule');
mymodule.init('http://localhost:27017/test');

// mymodule/index.js
var mongoose = require('mongoose');
module.exports = {
init: function(connString){
module.exports = connection = mongoose.createConnection(connString); // this is wrong
}
}

// mymodule/user.js
// I want to use the connection to create the mongoose 'User' model
var mongoose = require('mongoose');
var connection = require // I don't know
var UserSchema = new mongoose.Schema({
name: String
});

module.exports = connection.model('User', UserSchema);

感谢您的建议。

最佳答案

mongoose.createConnection() 是同步的,因此您应该能够从您的方法返回连接。

var mongoose = require('mongoose');
module.exports = {
init: function(connString){
return mongoose.createConnection(connString);
}
}

然后你可以这样做:

var module = require('myModule');
var db = module.init('mongodb://etc/db');

关于javascript - 模块参数的 Node js module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28147059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com