標籤:操作 update ports date ajax type 跨域 hand ring
廢話不錯說,直接看代碼:
首先下載mongodb
npm i mognodb --save 或者 cnpm i mongodb
在當前express項目裡面建立檔案夾db,然後建立test.js 資料庫連接檔案
// 連結 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('資料庫啟動成功!!!!');
在當前express項目找到app.js 在裡面引入該資料庫連接檔案
require('./db/test');var userlist = require("./db/test").userlist
使用當前表來做增刪改查操作
// 尋找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 串連 mongodb的做法