nodejs操作数据库mongodb

全部代码:
html代码:




   
   viewOne
   
   
   
   
   


viewTwo取消

后台代码:

var MongoClient = require('mongoose');
MongoClient.connect('mongodb://localhost:27017/node数据库',{ useNewUrlParser: true },function () {  //27017是数据库端口,node数据库是数据库名
    console.log('test')
});
//提示数据库是否链接成功
var db = MongoClient.connection;
db.on('open',function () {
    console.log('MongoDB链接成功')
})
db.on('error',function () {
    console.log('MongoDB连接失败');
})
var Schema = MongoClient.Schema; //创建一个Schema模型骨架,并且设置好user模版
var userSchema = new Schema({
    firstName:{type:String},
    lastName:{type:String}
});
var User = MongoClient.model("User",userSchema);  //Schema发布一个User的Model
app.get('/regist',function (req,res) {  处理regist的get请求
    console.log('轻取i成功')
    console.log(req.query.first_name)
    var user_1 = new User({
        firstName: req.query.first_name,
        lastName: req.query.last_name
    });
    user_1.save(function () {
        res.send('数据插入成功');  //插入数据并且提示数据库插入成功
    });
});

1、链接数据库:

var MongoClient = require('mongoose');
MongoClient.connect('mongodb://localhost:27017/node数据库',{ useNewUrlParser: true },function () {  //27017是数据库端口,node数据库是数据库名
    console.log('test')
});

//提示数据库是否链接成功
var db = MongoClient.connection;
db.on('open',function () {
    console.log('MongoDB链接成功')
})
db.on('error',function () {
    console.log('MongoDB连接失败');
})

2、创建一个Schema骨架模型,并且设计好user模板

var Schema = MongoClient.Schema; //创建一个Schema模型骨架,并且设置好user模版
var userSchema = new Schema({
    firstName:{type:String},
    lastName:{type:String}
});

3、发布模型

var User = MongoClient.model("User",userSchema);  //Schema发布一个User的Model

4、处理前端请求

app.get('/regist',function (req,res) {  处理regist的get请求
    console.log('轻取i成功')
    console.log(req.query.first_name)
    var user_1 = new User({
        firstName: req.query.first_name,
        lastName: req.query.last_name
    });
    user_1.save(function () {
        res.send('数据插入成功');  //插入数据并且提示数据库插入成功
    });
});

借鉴自:https://blog.csdn.net/qwe502763576/article/details/79646551
http://vince.xin/article/5acc33286b78214ab8ac58b6

你可能感兴趣的:(nodejs操作数据库mongodb)