使用express框架和mongoose在MongoDB新增数据

Posted on 2019-01-13 04:40  猫头唔食鱼  阅读(435)  评论(0编辑  收藏  举报

1.安装 express 

npm i express --save

 

2.安装 mongoDB

npm i mongodb --save

 

3.安装mongoose 

npm i mongoose --save

 

4.server.js中创建schema,shcema相当于sql的表,里面含有字段,可以定义自定类型,如String,Number等类型,

var schema = new mongoose.Schema({
    userName:{type:String,require:true},
    age:{type:Number,require:true}
});

 

5.创建model 。mongoose("自定义schema的名称",刚创建的schema)

var User = mongoose.model("user",sechma);

 

 

6.创建数据

User.create({

  userName:"ls",

  age:13

},function(err,doc){

  if(!err){
        
       console.log(doc)

    }else{
        console.log(err)

           }

});    

 

7.创建成功后运行 nodemon server.js ,会出现新添加的数据,如下图:

 

 

运行后,要注释第6步的代码,不然会重复创建数据

 

8.server.js完整代码:

const express = require('express');
const mongoose = require("mongoose");
const app = express();
const DB_URL  = "mongodb://localhost:27017"
mongoose.connect(DB_URL);
mongoose.connection.on("connected",function(){
    console.log("connect success");
    
});
var schema = new mongoose.Schema({
    userName:{type:String,require:true},
    age:{type:Number,require:true},
});
var User = mongoose.model("user",schema);
User.create({
    userName:"ls",
    age:13
},function(err,doc){
    if(!err){
        console.log(doc);
        
    }else{
        console.log(err);
        
    }
});
app.get("/",function(req,res){
    res.send("test");
});
app.get("/data",function(req,res){
    res.json({
        name:"zs",
        age:12
    });
});

app.listen(9090,function(){
    console.log("listening port 9090");
    
});