第一步,安装mongoose模块
npm i mongoose -S
第二步,导入模块
const mongoose = require("mongoose");
第三步,连接数据库
mongoose.connect("mongodb://127.0.0.1/tyqaq");//(ps:tyqaq是库名)
其他步,添加些监听
获得获取数据库连接
const conn = mongoose.connection;
添加监听数据库连接事件
conn.on("connected",()=> { console.log("数据库连接成功") })
Events:(其他事件)
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.
第四步,创建数据模型(集合,表)
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
查找&&写入数据
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里包含内容