使用时要先安装相关依赖,在目标文件夹中打开cmd,使用npm install mongoose
命令下载。
之后启动MongoDB。
在相应文件中引入mongoose
代码:
const mongoose=require("mongoose")
用mongoose连接数据库
代码如下
mongoose.connect("mongodb://localhost/database")
.then(()=>console.log("成功"))
.catch((err)=>console.log(err))
其中,database为自定义的,如果database不存在的话,MongoDB会自动创建,这里要特别声明一下,MongoDB的默认端口为27017。
之后要考虑实现的是数据库的增删改查,在这之前,先来学习如何创建表格,这里以User举个例子,User下有用户名,年龄和密码三个属性。代码如下:
//设定规则
const userSchema=new mongoose.Schema({
name:String,
password:String,
age:Number
})
//创建集合
const User=mongoose.model("User",userSchema);
这里也要说一点,创建的集合名字在MongoDB数据库中并不会是User,而是users。
并且,Schema中的属性不仅仅可以指定类型,还可以规定一些条件,这是就需要将其改为对象,例如name属性,可以写成:
name:{
type:String,
required: true, //必填项
minlength: 2, //最小长度
maxlength: 20 //最大长度
}
下面是可以添加的验证规则:
required: true 必传字段
minlength:字符串最小长度
maxlength: 字符串最大长度
min: 数值最小为2
max: 数值最大为100
enum: ['html', 'css', 'javascript', 'node.js']枚举
trim: true 去除字符串两边的空格
validate: 自定义验证器
default: 默认值
然后创建表单项,即“增”,代码如下:
//创建实例
const user=new User({
name:"le",
password:"2131132",
age:13
})
//保存
user.save();
另一种方法:
User.create({
name:"le",
password:"2131132",
age:13
})
这两种方法都会在生成的项目中自动添加_id属性,可以指定_id,但是要注意,如何_id属性添加时数据库中已经存在了此_id的值,则不会新增一个,而是在原有的基础上进行修改。
然后是删除,代码如下:
//删除一个,只删除满足条件的第一个列表项
User.findOneAndDelete({
//这里为查询条件
}).then(res=>console.log(res));//返回的是删除的数据
//删除多个
User.deleteMany({
//这里为查询条件
}).then(res=>console.log(res));//返回的是删除的数据
之后是更改,贴上代码
// 更新单个
User.updateOne({/*查询条件*/}, {/*要修改的值}*/).then(result => console.log(result))
// 更新多个
User.updateMany({/*查询条件*/}, {/*要更改的值*/}).then(result => console.log(result))
查询的小地方就比较多了,让我们来看一看代码:
// 根据条件查找文档(条件为空则查找所有文档)
User.find().then(result => console.log(result))
// 根据条件查找文档
User.findOne({name: 'node.js基础'}).then(result => console.log(result))
//匹配大于 小于
User.find({age: {$gt: 10, $lt: 50}}).then(result => console.log(result))
//匹配包含
User.find({name: {$in: ['le']}}).then(result => console.log(result))
//选择要查询的字段
User.find().select('name age').then(result => console.log(result))
//将数据按照年龄进行排序
User.find().sort('age').then(result => console.log(result))
//skip 跳过多少条数据 limit 限制查询数量
User.find().skip(2).limit(2).then(result => console.log(result))
联合查询:两个不同表中的数据有关联,要通过一个表中的数据找到另一个表的数据,需要使用populate方法,举个例子:
// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } }));
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
title: { type: String },
// 使用ID将文章集合和作者集合进行关联
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
.populate('author')
.then((err, result) => console.log(result));
若直接查询Post表则不会返回正确的author值,通过populate取到对应值后输出即为期望值。
大概就是这些,有错误请评论指出,若想了解更多,可以去看官方文档