使用react nodejs和ajax更新mongodb的文档

时间:2015-06-22 09:15:09

标签: ajax node.js mongodb reactjs

我开始用nodejs练习react和mongodb。 通过使用react我在nodejs的帮助下获取数据... 现在我试图在nodejs ....

的帮助下更新或删除mongodb的文档

我在nodejs中为他们编写了服务,但我没有得到任何关于如何将它与React连接的线索。

Plz帮我解决了这个问题。

提前致谢...

1 个答案:

答案 0 :(得分:2)

如果你去反应网站,看看他们的教程,他们就有一个很好的ajax调用示例。

基本上你首先编写你的ajax函数,如果它是GET请求它可能看起来像这样:

你的nodejs代码:

//the route we get our users at is allUsers
app.get('/allUsers, function(req, res) { 
User.find({}, function(err, userarray) { //we grab all users from our mongo collection, and that array of users is called userarray
      res.json(userarray); //we return the json with it
  });
});

现在为反应部分:

var Users = React.createClass({

getUsers : function() { //we define a function for getting our users

   $.ajax({ //call ajax like we would in jquery
            url: '/allUsers',  //this is the url/route we stored our users on
            dataType: 'json',
            success: function(data) { //if we get a Success for our http get then..
               this.setState({user:data}); //set the state of our user array to whatever the url returned, in this case the json with all our users
               }.bind(this),
        error: function(xhr, status, err) { //error logging and err tells us some idea what to debug if something went wrong.
                console.log("error");
               console.error(this.props.url,status, err.toString());
            }.bind(this)
        });

   },

getInitialState: function() { //setting our initial state for our user array we want to use in our react code
       return {

          users: [], //initialize it empty, or with whatever you want

       }
    },

componentDidMount : function() {
this.getUsers(); //we are invoking our getUsers function here, therefore performing the ajax call
},

render : function() {
return(
//do what we want to do with our array here I guess!
<div>

<PrintArray users = {this.state.users} />

</div>
)
}
});
//Our new Class called Printarray
var PrintArray = React.createClass({
render : function() {
    //Psuedocode
    return(
     ul {
       this.props.users.map(function(user){  //we are mapping all our users to a list, this.props.users is inheritance what we passed down from our Users class
            return (
            <li key = user.id> user.name </li>
            )
      })

     )
}
    </ul>
});

然后最后调用我们的主类,

React.render(<Users   />,
document.getElementById(domnNode)); //your div's id goes here

我已经注释掉了代码,如果您有任何问题可以随意提问!我不知道你是否想做一个post方法,但它的相似之处。你只需将GET更改为POST,而不是没有参数的函数,你很可能想要一个参数,所以它可能是这样的:

sendNewUser : function(data) {
 //do ajax post stuff here
}

并在渲染中:

render : function(){
   sendNewUser(blah);
}

除了你可能有一个表格或某个东西,甚至是另一个处理添加新用户的类。问题似乎非常广泛,所以我只是概述了我将如何做到这一点!