Get started with node. js, Express, MongoDB (based on Easyui DataGrid additions and deletions)

Source: Internet
Author: User
Tags bulk insert mongodb server install node


Objective


From the installation of the environment in the native (win8.1) environment to finish this demo about less than two weeks, just started in the local installation environment and did not knock a demo, from the beginning of the weekend and intermittent to write a, according to the inertia of thinking to write a deletion and change to check it, One is to experience the magic of node. JS, and the second is to look at the API of node. JS, Express, and Mongoose, followed by the process of documenting yourself, making it easy for you to see, and then a guide for your friends to get started.



The most refreshing thing about the demo is that NPM (Node Package manager) is a node. JS Management and Distribution tool. You need to install any third-party library, install it directly with NPM, and it's handy, such as Mongoosee (MongoDB Drives in node. js).





node. JS Express MongoDB Installation


1. Install node. js to facilitate development or configure environment variables



Http://www.runoob.com/nodejs/nodejs-install-setup.html



2. Install Express



http://blog.csdn.net/u013310075/article/details/22592787



3. Installing MongoDB



Http://www.cnblogs.com/lsc183/archive/2012/08/16/mongodb.html


Development environment


1. Create an express project with a DOS command and install a third-party dependent library using NPM.



2. Start the MongoDB server with DOS and insert the test data with DOS boot client.



3, with sublime text2 development. In the demo process, a friend suggested that I use webstorm development, because can quickly locate the problem.





Precautions


1. Create a project with DOS EXPRESS-E demo CD demo NPM Install (third-party dependent libraries in Package.json). The-e description uses the Ejs template, but it is modified into HTML in the project.



2, install mongoose driver npm Install Mongoose--save (--save install update Package.json configuration information).



3, in DOS BULK insert data var listarr=[];for (i=0;i<=5;i++) {Listarr.push ({"Stuname": "Stu" +i, "age": 20+i, "sex": "Male", "address" : "China"}), enter will prompt 6,



Input Db.students.insert (Listarr) Enter will appear bulkwriteresult information, that is, batch creation completed, using Db.students.find () to view all data.



4, if directly get the ID in MongoDB, then in index.js to get the need to do a conversion: Var id=mongoose. Types.objectid (req.params.id); Req.params.id is also easy to write Req.param.id.





Example
















Key Code 1, Mongodb.js (equivalent to our common DAO layer)

var mongoose = require (‘mongoose’);
var db = mongoose.connect (‘mongodb: // localhost: 27017 / test’); // Connect to the test database

var Schema = mongoose.Schema; // Create model
var studentSchema = new Schema ({
stuname: String,
age: Number,
sex: String,
address: String
});

studentSchema.methods.addStu = function (student, callback) {
this.stuname = student.stuname;
this.age = student.age;
this.sex = student.sex;
this.address = student.address;
this.save (callback);
}


var student = db.model (‘students’, studentSchema);
//exports.student=student;
module.exports = student;
 

2. index.js (routing)
var express = require (‘express’);
var router = express.Router ();
var mongoose = require (‘mongoose’);

var student = require (‘./../ database / mongodb.js’);

/ * GET home page. * /
router.get (‘/‘, function (req, res, next) {
   res.render (‘index‘, {title: ‘Index‘});
});


router.post (‘/ index / list’, function (req, res) {
var students = student.find (function (err, result) {
   if (err) {
   res.send (err);
   } else {
   res.json (result);
   }
   });
});

router.post (‘/ index / add’, function (req, res) {
var obj = req.body;
var stu02 = new student ();
stu02.addStu ({
stuname: req.body.stuname,
age: req.body.age,
sex: req.body.sex,
address: req.body.address
}, function (rs) {
res.json ({success: true});
});
});

router.post (‘/ index / delete‘, function (req, res) {
var id = req.body.id;
The
student.remove ({_ id: id}, function () {
res.json ({success: true});
});
})

router.post (‘/ index / edit /: id’, function (req, res) {
console.log (‘aa‘);
var id = mongoose.Types.ObjectId (req.params.id);

student.update ({_ id: id}, {$ set: {stuname: req.body.stuname, age: req.body.age, sex: req.body.sex, address: req.body.address}}, function (err, rs) {
if (err) {
console.log (err);
} else {
res.json ({success: true});
}
The
});

})

module.exports = router;
 

3. index.html
<! DOCTYPE html>
<html>
  <head>
     <title> <% = title%> </ title>
     <link rel = "stylesheet" type = "text / css" href = "/ javascripts / jquery-easyui-1.4.4 / themes / default / easyui.css">
<link rel = "stylesheet" type = "text / css" href = "/ javascripts / jquery-easyui-1.4.4 / themes / icon.css">
     <script type = "text / javascript" src = "/ javascripts / jquery-easyui-1.4.4 / jquery.min.js"> </ script>
     <script type = "text / javascript" src = "/ javascripts / jquery-easyui-1.4.4 / jquery.easyui.min.js"> </ script>
<script type = "text / javascript" src = "/ javascripts / jquery-easyui-1.4.4 / locale / easyui-lang-zh_CN.js"> </ script>
  </ head>
  <body>
  <div id = "tb">
    <div>
<a href="javascript:openUserAddDialog()" class="easyui-linkbutton" data-options="plain:true,iconCls:‘icon-add‘"> Add user </a>
<a href="javascript:openUserModifyDialog()" class="easyui-linkbutton" data-options="plain:true,iconCls:‘icon-edit‘"> Edit user </a>
<a href="javascript:deleteUser()" class="easyui-linkbutton" data-options="plain:true,iconCls:‘icon-delete‘"> Delete user </a>
    </ div>
  </ div>
<table id = "dg" title = "Student Management" class = "easyui-datagrid" style = "width: 500px;" singleSelect = "true" idField = "_ id" rownumbers = "true"
       url = "/ index / list" fit = "true" toolbar = "# tb">
    <thead>
<tr>
<th field = "cb" checkbox = "true" align = "center"> </ th>
<th field = "_ id" width = "250" align = "center"> ID </ th>
<th field = "stuname" width = "100" align = "center"> Name </ th>
<th field = "age" width = "50" align = "center"> Age </ th>
<th field = "sex" width = "100" align = "center"> Gender </ th>
<th field = "address" width = "100" align = "center"> Address </ th>
The
</ tr>
    </ thead>
</ table>

<div class = "easyui-dialog" id = "dlg" style = "width: 480px; height: 330px; padding: 10px 10px;" closed = "true" buttons = "# dlg-buttons" data-options = "" >
    <form action = "" method = "post" id = "fm">
        <table cellspacing = "8px" align = "center">
            <tr>
            <input type = ‘hidden‘ id = "_ id" name = "_ id" />
                <td> Name: </ td>
                <td> <input type = "text" id = "stuname" name = "stuname" required = "true" style = "width: 300px;" /> </ td>
                <td> </ td>
            </ tr>
            <tr>
                <td> Age: </ td>
                <td> <input type = "text" id = "age" name = "age" required = "true" /> </ td>
                <td> </ td>
            </ tr>
            <tr>
                <td> Sex: </ td>
                <td> <input type = "text" id = "sex" name = "sex" required = "true" /> </ td>
                <td> </ td>
            </ tr>
            <tr>
                <td> Address: </ td>
                <td> <input type = "text" id = "address" name = "address" required = "true" /> </ td>
                <td> </ td>
            </ tr>
            
        </ table>
    </ form>
</ div>


<div id = "dlg-buttons">
    <a href="javascript:saveUser();" class="easyui-linkbutton" iconCls="icon-ok"> Save </a>
    <a href="javascript:closeUserDialog();" class="easyui-linkbutton" iconCls="icon-cancel"> Cancel </a>
</ div>
  </ body>
<script type = "text / javascript">
var url = "";
function saveUser () {
            $ (‘# Fm‘). Form (‘submit’, {
                url: url,
                onSubmit: function () {
                    
                },
success: function (result) {
                    var result = eval (‘(‘ + result + ‘)’);
                    if (result.success) {
                        $ .messager.alert ("System Prompt", "Save Successful");
                        $ ("# fm"). form ("reset");
                        $ ("# dlg"). dialog ("close");
                        $ ("# dg"). datagrid ("reload");
                    } else {
                        $ .messager.alert ("System prompt", "Save failed");
                        return;
                    }
                }
            });
        }

         function closeUserDialog () {
            $ ("# dlg"). dialog ("close");
            $ ("# fm"). form ("reset");
        }

          function deleteUser () {
            var selectedrow = $ ("# dg"). datagrid (‘getSelected’);
            if (selectedrow == null) {
                $ .messager.alert ("System prompt", "Please select the data to delete!");
                return;
            }
            
            var id = selectedrow._id;
            $ .messager.confirm ("System prompt", "Are you sure you want to delete this data?", function (r)
                if (r) {
                    $ .post ("/ index / delete", {id: id}, function (result) {// result directly returns Object, so there is no need to convert to json
                        if (result.success) {
                            $ .messager.alert ("System Prompt", "Data has been successfully deleted!");
                            $ ("# dg"). datagrid ("reload");
                        } else {
                            $ .messager.alert ("System prompt", "Data deletion failed!");
                        }
                    }, "json");
                }
            });
        }

function openUserAddDialog () {
            $ ("# fm"). form ("reset"); // Clear data before opening
            $ ("# dlg"). dialog ("open"). dialog ("setTitle", "Add User");
            url = "/ index / add";
        }

     function openUserModifyDialog () {
            var selectedrow = $ ("# dg"). datagrid (‘getSelected’);
            if (selectedrow == null) {
                $ .messager.alert ("System Prompt", "Please select a piece of data to modify");
                return;
            }
            
            $ ("# dlg"). dialog ("open"). dialog ("setTitle", "Modify user information");
            dispValue (selectedrow);

            url = "/index/edit/"+selectedrow._id;
        }

        function dispValue (row) {
        The
            $ ("# stuname"). val (row.stuname);
            $ ("# age"). val (row.age);
            $ ("# sex"). val (row.sex);
            $ ("# address"). val (row.address);
        }
</ script>
</ html>
 

References
 1. http://www.cnblogs.com/caiya928/p/4776437.html node.js express sql server addition, deletion and modification.

 2. http://www.cnblogs.com/hubwiz/p/4118083.html

 3. http://www.cnblogs.com/highsea90/p/4308794.html

 4. https://cnodejs.org/topic/535601a20d7d0faf140303d8

 5. http://blog.csdn.net/jessonlv/article/details/17379535

 

to sum up
     This demo is an add, delete, and modify query written by connecting to mongodb. I originally wanted to write an add, delete, and modify query based on sql server. I put this code first based on the reason that the time is not fixed. With a demo, I have some questions about the syntax. After throwing it out, taking these questions to check the API or go to the node.js tutorial will speed up the learning speed and save time and cost. During the demo, I also recorded some txt, mainly for the unfamiliar node operation or forget how to operate express, mongoose. Friends who need to communicate again. Attach the code http://pan.baidu.com/s/1kTCQyUz

 

Getting started with Node.js, express, mongodb (addition, deletion, and modification based on easyui datagrid)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.