第一步,安裝mongoose模塊node
npm i mongoose -S
第二步,導入模塊ios
const mongoose = require("mongoose");
第三步,鏈接數據庫mongodb
mongoose.connect("mongodb://127.0.0.1/tyqaq");//(ps:tyqaq是庫名)
其餘步,添加些監聽
得到獲取數據庫鏈接數據庫
const conn = mongoose.connection;
添加監聽數據庫鏈接事件npm
conn.on("connected",()=> { console.log("數據庫鏈接成功") })
Events:(其餘事件)json
connecting: Emitted when connection.{open,openSet}() is executed on this connection.
connected: Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.
open: Emitted after we connected and onOpen is executed on all of this connections models.
disconnecting: Emitted when connection.close() was executed.
disconnected: Emitted after getting disconnected from the db.
close: Emitted after we disconnected and onClose executed on all of this connections models.
reconnected: Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.
error: Emitted when an error occurs on this connection.
fullsetup: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.
all: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
For practical reasons, a Connection equals a Db.api
第四步,建立數據模型(集合,表) mongoose
exports.User = mongoose.model("users",{ account:String, password:String, photo:String, createTime:Date, ip:String });
或者這樣寫函數
// name : { type:String },//屬性name,類型爲String // age : { type:Number, default:0 },//屬性age,類型爲Number,默認爲0
查找&&寫入數據post
router.post("/api/user/register", (req, res) => { // 查找集合內account字段 有多少個 若是大於0表示帳戶存在,也就不寫入 db.User.find({ account: req.body.account }).count(function (err, count) { if (count > 0) { res.json({ code: "fail", message: "賬戶名存在!" }) } else { //不大於0表示不存在 準備導入庫 req.body.createTime = new Date(); req.body.ip = tools.formatIP(req.ip); // 使用數據模型類建立一個用戶對象,而且填充數據 var user = new db.User(req.body); // 調用save方法將數據保存到數據庫中 // 數據模型表示一類事物,它能夠包含數據,還包含相應的數據操做方法 user.save(function (err, model, count) { // console.log(arguments); if (err) { res.json({ code: "error", message: "服務端錯誤,請稍候在試!" }) } else { res.json({ code: "success", message: "註冊成功!" }) } }) } }) })
//建立一個篩選對象 var filter = { account:req.body.account, password:req.body.password } // 根據篩選條件查找。執行回調函數, db.User.find(filter).exec(function (err,models) {
err存在數據庫出錯,不存在查看 models裏包含內容