Good nonsense to say, look directly at the code:
First Download MongoDB
npm i mognodb --save 或者 cnpm i mongodb
Create a new folder in the current Express project DB, and then create a new test.js database connection file
// 链接 firstblood 集合var mongoose = require('mongoose');var db = mongoose.createConnection('mongodb://localhost:27017/firstblood');// 链接错误db.on('error', function(error) { console.log(error);});// Schema 结构var Schema = mongoose.Schema;//表一var userlistScheMa = new Schema({ user : String, password : String, //content : {type : String}, //time : {type : Date, default: Date.now}, age : Number, name : String, phone : String, address : String, numbers : String,});// 关联 userlist -> admins 表 表数据有问题,一切都白搭!//表一exports.userlist = db.model('admins', userlistScheMa,'admins');exports.db = db;console.log('数据库启动成功!!!!');
Find App.js in the current Express project to introduce the database connection file inside
require('./db/test');var userlist = require("./db/test").userlist
Use the current table to do additions and deletions and change the operation
// 查找userlist.find({查找值名: 传入当前搜索值},fucntion(err, docs){ console.log(docs)})// 修改userlist.update({ 修改值名 : 传入当前修改值}, { user:req.query.user, password: req.query.password, age: req.query.age, numbers: req.query.numbers, name: req.query.name, phone: req.query.phone, address: req.query.address // 更新操作}, function(error) {});// 删除userlist.remove({ 删除值名: 传入需要删除的值}, function(err,docs) { if (err) return handleError(err); // removed!});// 增加var userlist2 = new userlist({ 增加值名: 增加值, 增加值名: 增加值})userlist2.save(function(err,docs){ /**设置响应头允许ajax跨域访问**/ res.setHeader("Access-Control-Allow-Origin","*"); /*星号表示所有的异域请求都可以接受,*/ res.setHeader("Access-Control-Allow-Methods","GET,POST"); if(err){ res.send('1') }else{ res.send('保存成功!') }})
Express connection to MongoDB practice