在多个文件中使用 Mongoose 连接到 MongoDB

joe*_*oec 2 mongoose mongodb node.js webpack react-redux

我是使用 mongoose 和 MongoDB 的新手。我正在开发一个 React-Redux 应用程序来保存待办事项列表。我正在使用 webpack 来捆绑所有内容。

连接到多个文件中的 MongoDB 的最佳方式是什么?例如,当我最初的app.jsx运行,然后在我的reducers.jsx文件中保存到数据库......

我知道猫鼬保持持久连接,但每当我尝试使用

var mongoose = require('mongoose');

我收到此 webpack 错误

WARNING in ./~/mongoose/lib/drivers/index.js Critical dependencies: 8:11-74 the request of a dependency is an expression @ ./~/mongoose/lib/drivers/index.js 8:11-74

当我创建一个单独的测试应用程序时,我可以使用成功写入 MongoDB

mongoose.connect() and the .save() methods,当所有内容都保存在一个文件中时。

谢谢

应用程序.jsx

var React = require ('react');
var ReactDOM = require ('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require ('react-router');

var {Provider} = require('react-redux');

var TodoApp = require('TodoApp');

var actions = require('actions');
var store = require('configureStore').configure();
var TodoAPI = require('TodoAPI');


// Connect to MongoDB using mongoose
var url = 'mongodb://joe:test@ds147487.mlab.com:47487/reacttodo';
var mongoose =require('mongoose');
mongoose.connect(url);


store.subscribe(()=>{
  var state = store.getState();
  console.log('new state',state);
  TodoAPI.setTodos(state.todos);
});

var initialTodos = TodoAPI.getTodos();
store.dispatch(actions.addTodos(initialTodos));

// load foundation
$(document).foundation();

//app css
require('style!css!sass!AppStyles');

ReactDOM.render(
  <Provider store={store}>
    <TodoApp/>
  </Provider>,
  document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

And*_*M16 6

您需要Mongoose在您的系统中要求并打开一个到它的新连接server.js,以便您可以通过不同的模块访问它。

假设您同时使用expressbody-parser

服务器.js:

. . .
var mongoose   = require('mongoose');
var port       = process.env.PORT || 3000;
var express    = require('express');
var bodyParser = require('body-parser');
. . .
var app             = express();
mongoose.connect("mongodb://localhost/MyApp");
. . .
app.use(bodyParser.json());
. . .
require('./app/routes.js')(app);
app.listen(port);
console.log('App listening on port ' + port);
Run Code Online (Sandbox Code Playgroud)

然后,您就可以轻松访问它。假设您想要设置一个mongoose schema.

mySchema.js:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var user = new Schema({
          name: {type: String, required : true}
});

module.exports = mongoose.model('user', user);
Run Code Online (Sandbox Code Playgroud)

或者您只想检索所有用户或将新用户保存到用户集合中,假设您向其传递一个req具有名称等属性的对象:

用户工厂.js

require('mongoose');
var User = require('mySchema.js');

exports.getUsers = getUsers;
exports.postUser = postUser;

function getUsers() {
  return new Promise( function (resolve, reject) {
    var query = User.find({});
    query.exec(function(err, users) {
        if (err){
            return reject({err : 'Error while fetching users'});
        }
        // If no errors are found, it responds with a JSON of all users
        return resolve(users);
     });
  });
}



function postUser(req) {
    return new Promise( function (resolve, reject) {
    // Creates a new User based on the Mongoose schema and the post body
      var newUser = new User(req.body);
      // New User is saved in the db.
      newUser.save(function(err) {
          console.log('err',err);
          if (err){
              return reject({err : 'Error while saving new user'});
          }
          // If no errors are found, it responds with a JSON of the new users
          return resolve(req.body);
      });
    });
}
Run Code Online (Sandbox Code Playgroud)

另外,假设您想设置一条路由来拦截http请求。例如,保存新用户的请求。

路线.js:

var UserFactory = require('./factories/user.factory.js');

// Opens App Routes
module.exports = function(app) {

   /** Getting all the users **/
   app.get('/users', function(req, res) {
     UserFactory.getUsers().then( function (users) {
        res.json(users);
     }, function (error) {
        res.json(error);
     });
   });

   /** Posting a new geometry **/
   app.post('/users', function(req, res) {
     UserFactory.postUsers(req).then( function (user) {
        return res.json(user);
     }, function (error) {
        res.json(error);
     });
   });

}
Run Code Online (Sandbox Code Playgroud)

并且,在前端,用户在表单中插入用户名,然后单击提交按钮,然后调用一个createNewUser函数:

. . .
var createNewUser = function(userName){

   var user = {
                  name : userName //Goofy
   };

   console.log(user.name); //Goofy

   postNewUser(user).then( function( response, err){
     if(err){
       console.log('Error while saving new user');
     } else {
       console.log('User '+response+' successfully saved');
     }
   });

}

function postNewUser(user){
  return new Promise(function (resolve, reject) {
     // Saves user data to the db
     $http.post('/users', user)
          .success(function(res) {
            if(res.error){
               return reject(res.error);
            }
               return resolve(res);
     });
   });
  }
Run Code Online (Sandbox Code Playgroud)

您还可以在server.js中全局设置 mongoose ,这样您就不需要在模块中 require 它

var mongoose = require('mongoose');
. . .
global.mongoose = mongoose;
Run Code Online (Sandbox Code Playgroud)

希望我有所帮助。