1. 程式人生 > 其它 >node.js連結MongoDB資料庫初體驗之新增一條資料

node.js連結MongoDB資料庫初體驗之新增一條資料

技術標籤:node.jsnode.jsmongodbjavascript

入門

教程連結:https://www.runoob.com/mongodb/mongodb-window-install.html

需要:node.js 和monggodb環境

one

下載安裝mongodb並啟動

教程連結:https://www.runoob.com/mongodb/mongodb-window-install.html

two

npm第三方外掛 mongoose

	npm install mongoose --save

實現新增向資料庫新增一條資料

// 1-載入mongoose模組
const mongoose =
require("mongoose") // 將mongodb.Schema賦值給 Schema 下面可直接new出SChema例項 const Schema =mongoose.Schema //2-連結本地資料庫,要確保資料庫處於開啟狀態,其中test為資料庫的庫名 mongoose.connect('mongodb://localhost/test') //3-設計資料庫的集合結構(架構),你可以理解為對資料的約束 // 設定資料的約束,防止髒資料產生 // 欄位名就是資料庫中的屬性名(下面以個人資訊為例子) // 建立一個Schema的例項student,並約束o const studentSchema =
new Schema({ name:{ type:String , //約束名字的資料型別為字串 require:true //必須要有,就是非空 }, //因為在nodejs中,所以資料型別可以是javascript中任意資料型別 age:{ type:Number,//約束年齡的資料型別為數字 require:true//同上 }, id:{ type:Number, require:
true } }); //4-將剛才設定的文件結構(資料約束)釋出為模型使用mongoose.model()方法 //mongoose.model(引數1,引數2) 返回一個數據模型建構函式 //引數1:傳入一個大寫單數字符串來表示你資料庫的表的名稱 // mongoose會自動將大寫的字串變為小寫複數的字串來表示你的表名稱 //例如這裡的 Student 會變成 students //引數2:傳入一個集合結構(架構/約束) // 返回值 返回一個數據模型建構函式 const Student =mongoose.model('Student',studentSchema) //當我們有了他之後我們就可以對students表中的資料進行操作了(增,刪,改,查) //1.增 //將剛才獲得的建構函式模型直接例項化並用一個變數接收 const student1 =new Student({ name:"小明", //資料庫內需要要的資料, age:18, //注意!此時傳入的資料要符合你studentSchema架構中約束 id:01 }) //呼叫save()方法,將你傳入的資料儲存進資料庫 student1.save((err,data)=>{ if(err){ console.log("存入失敗,請檢查資料型別"); //失敗的回撥 }else{ console.log('儲存成功,儲存的資料是'+data);//成功的回撥 } })

執行顯示成功!
示例
去資料庫查詢結果
結果
成功!

參考文件(api)連結

https://mongoosejs.com/docs/guide.html