Mongoose 应用 随笔

第一步,安装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里包含内容

时间: 2024-08-17 12:00:33

Mongoose 应用 随笔的相关文章

C#博客随笔之六:数据绑定

这一篇随笔记录的是在完成程序中遇到的一些情况 首先要讲的是MVVM 所谓MVVM就是Model,View,ViewModel 下面是MVVM的优点(引用自百度百科): MVVM模式和MVC模式一样,主要目的是分离视图(View)和模型(Model),有几大优点1. 低耦合.视图(View)可以独立于Model变化和修改,一个ViewModel可以绑定到不同的"View"上,当View变化的时候Model可以不变,当Model变化的时候View也可以不变.2. 可重用性.你可以把一些视图

Abby's 学习php5随笔

2017.6.27 Abby's cakephp2 学习之旅 下载了XAMPP集成开发环境,然后配置其数据库,参考学习教程, 1.建立表单. 配置完信息如下,Cache Apache默认在windows下是system用户,所以权限最高,但xampp集成环境中的apache确是administor 如何更改apache用户为system 静默开发.(一种开发方法,番茄ToDo中的学霸模式有些相似) 如何设置.ctp的显示 http://cakephp2.local/posts/index怎么就可

java基础随笔 字符数据类型char的单引号

public class Love{ public static void main(String[] args){ System.out.println('*'+'\t'+'*'); System.out.println("*"+"\t"+"*") } } 运行结果   第一行为  93 第二行为  *        * 原因 第一行中'\t' 单引号  识别为字符数据类型char,char类型是可以运算的,在第一行中+做了运算符. 第二行&q

mongoose 全面理解

一.创建schemas 创建schemas的方式: 1 var userSchema = new mongoose.Schema({ 2 name: String, 3 email: String, 4 createdOn: Date 5 }); schemas中的数据类型有以下几种:? String? Number? Date? Boolean? Buffer? ObjectId? Mixed? Array 特别需要说明一下ObjectId类型和Mixed类型以及Array类型,在schema

web前端学习随笔

好好算下来,学习web前端已有半个月了,这半个月来主要学习的是HTML和CSS部分,期间有困惑,也有解决困惑时的快感,所以想把这段时间感受到的一些东西记下来,因为内容比较杂,所以干脆叫随笔吧.这里面不会说前端的相关基础知识,只是说一些自己对前端的一些认识. html是用来控制页面结构的我曾经对这句话有过疑问,觉得html应该是控制页面内容的,为什么要说是控制页面结构的呢?在查看京东首页的代码时,我恍然大悟,html确实是定义页面内容的,但同时它也要控制页面的结构.举例来说,京东商品分类的div包

JavaWeb学习随笔

Servlet学习随笔 1.HttpServlet init(ServletConfig)------Servlet生命周期中的初始方法,默认情况是服务器创建后第一次访问这个Servlet时调用,可以修改配置信息,使其在服务器一创建时就被调用; 修改配置信息的方法-----在web.xml的<servlet>下添加<load-on-startup>x<load-on-startup>,x是正整数,越小表示优先级越高 url路径的配置,完全匹配>目录匹配>(.

mongoose中给字段添加索引的方法

mongoose中给字段添加索引的方法有两种,一种通过在定义schema的时候配置,如: 1 var animalSchema = new Schema({ 2 name: String, 3 type: String, 4 tags: { type: [String], index: true } 另一种通过index方法添加索引,如给name和type字段添加索引(1和-1分别表示升序索引和降序索引): animalSchema.index({ name: 1, type: -1 });

想知道博客园随笔总阅读量吗?

我真的是闲的无聊了...,前提是你写的随笔总数少于等于40条. 0.在选项里设置一页显示40条随笔 1,打开自己的随笔列表:https://i.cnblogs.com/posts 2,在当前页面f12打开浏览器控制台 3,粘贴进去以下代码 var trs=document.querySelectorAll('#post_list tr td:nth-child(4)')//取得阅读量 atrs=Array.from?Array.from(trs):Array.prototype.slice.ca

随笔1104

随笔1104 一.变量定义 var a = 10; 如果定义小数或整数的变量,等号后面值直接写 如果定义字符串的变量,等号后面的值要加双引号或单引号 类型转换 parseInt(); 强制转换为整数 parseFloat();强制转换为小数 二.运算符表达式 1.数学运算符 + - * / % 百分号是取余 例:alert(a+b); alert(a%b); a除以b的余数 2.逻辑运算符 && 并 指两者都满足 || 或 指两者其中任何一个满足 ! 非 指强制变反 真变假 假变真 3.比