Nodejs is a very powerful language, think and node want to contact the database I still like MongoDB, the following describes how to operate:
1. Download MongoDB on the official website, then install the Fool one-click
2. Under the path of installing the MongoDB package, the bin is run with cmd
Mongod--dbpath= f:\ your node project path
So your MongoDB is connected,
3. Run npm install MongoDB--save in your project
4. Run the following code in your project
// loading the database module // Listen for htttp request mongoose.connect ('mongodb://localhost:27017/node,function (err) { if (err) { Console.log ("Database link Failed"); } else{ console.log (' database link succeeded ') app.listen (8080); }});
5. Create a data sheet: the structure you want
// table data structure for storage classifications Let Mongoose = require (' Mongoose '); let Schema=Mongoose. Schema;constcity =new Schema ({ title:string, address:string}) Module.exports= Mongoose.model ("City", City, "City");
6. Create a JS file in another file and introduce this file to create the data table
Let city= require ('.. /city ');//AddfunctionAdd () {const City=NewCity ({title:Zhejiang, Address:Shanghai}) City.save (function(err,body) {if(Err) {Console.log (err); }Else{console.log (Body)}});}//FindfunctionSelect (contion) {city.find ({body:contion},function(){ if(Err) {Console.log (err); }Else{console.log (res); } });}//Editfunctionedit () {city.update ({},{body:' Address '},{multi:true},function(Err,raw) {if(Err) {Console.log (err); }Else{Console.log (raw); } })}//DeletefunctionDel () {
then in addition to your individual JS file introduced this method, in fact, you do not have to introduce, you can write your own so the database operation
Summary below:
- Define schema, which the schema publishes Model to manipulate the database.
- Model creates entity entities and can call the Save () method to save the data to the database.
- The Model.find () method queries all the data under the Schema, FindOne () queries the data based on the criteria, and FindByID () queries the data based on the ID.
- Model.limit () reads a specified number of data records.
- The Model.skip () method skips the specified number of data, and the general data is used more often for paging.
- Model.remove () deletes the data.
Nodejs manipulating the MongoDB database