我是使用mongoose和MongoDB的新手。我正在开发一个用于保存Todo列表的React-Redux应用程序。我使用webpack捆绑所有内容。
在多个文件中连接MongoDB的最佳方法是什么?例如,当我的初始app.jsx运行时,然后在我的reducers.jsx文件中保存到数据库...
我知道mongoose保持持久连接,但每当我尝试使用
时 var mongoose = require('mongoose');
我收到此网络包错误
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,
当所有内容都保存在一个文件中时。
由于
App.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')
);
&#13;
<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>
&#13;
答案 0 :(得分:2)
您需要Mongoose
并在server.js
中打开与其的新连接,以便您可以通过不同的模块访问它。
假设您同时使用表达和正文解析器
<强> server.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);
然后,您可以轻松访问它。我们假设您要设置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);
或者您只想检索所有用户或将新用户保存到用户集合,假设您向其传递了一个对象req
,该对象具有一些属性,如名称:
<强> user.factory.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);
});
});
}
此外,假设您要设置拦截http
请求的路由。例如,保存新用户的请求。
<强> routes.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);
});
});
}
并且,在前端,用户在表单中插入用户名,然后单击“提交”按钮并调用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);
});
});
}
您还可以在 server.js 中全局设置mongoose,这样您就不需要在模块中使用它了
var mongoose = require('mongoose');
. . .
global.mongoose = mongoose;
希望我一直很有帮助。