mongose操作数据库 增删改

//引入mongoose第三方模块 用来操作数据库
const mongoose = require(‘mongoose’);
//数据库连接
mongoose
.connect(‘mongodb://localhost/playground’, { useNewUrlParser: true })
.then(res => {
//连接成功
console.log(‘数据库连接成功’);
})
.catch(err => {
console.log(‘数据库连接失败’);
});

//创建集合规则
const userSchame = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String],
});
//使用规则创建集合 1.集合名称 2.集合规则
const User = mongoose.model(‘User’, userSchame); //courses

// //创建构造函数的实例
// const course = new User({
// name: ‘大四1’,
// age: 41,
// email: ‘44444’,
// password: 44444,
// hobbies: [‘听音乐’],
// });
// //将文档插入到数据控中
// course.save();

//查询用户集合中的所有文档
// User.find().then(res => console.log(res));
// 62aaab3d0d67056a0659857f
//通过_id字段查找文档 find返回一组 findOne返回一个
// User.find({ _id: ‘62aaab3d0d67056a0659857f’ }).then(res => console.log(res));

//findOne方法返回一条文档 默认返回当前集合中的第一条文档
// User.findOne({ _id: ‘62aaab3d0d67056a0659857f’ }).then(result =>
// console.log(result)
// );
//$gt大于 $lt小于 查询用户集合中年龄字段大于20并且小于40的文档
// User.find({ age: { $gt: 20, $lt: 40 } }).then(res => {
// console.log(res);
// });
//匹配包含
// User.find({ hobbies: { $in: [‘1’] } }).then(result => {
// console.log(result);
// });
//查询用户的名字和邮箱字段》
//选择要查询的字段
// User.find()
// .select(‘name email’)
// .then(result => {
// console.log(result);
// });
//将数据按照年龄进行升序排序
// User.find()
// .sort(‘age’)
// .then(result => {
// console.log(result);
// });
//将数据按照年龄进行降序排序
// User.find()
// .sort(‘-age’)
// .then(result => {
// console.log(result);
// });
//skip跳过多少条数据 limit限制查询数量
// User.find()
// .skip(2)
// .limit(3)
// .then(res => {
// console.log(res);
// });
//删除单个
//查找到一条文档并且删除 返回删除的文档。如果匹配多个 会删除第一个
// User.findOneAndDelete({ _id: ‘62aac8c000556e5074ba73e5’ }).then(res => {
// console.log(res, ‘res’);
// });
//删除多个 空{}会全部删除。。 返回对象 如 {n:4,ok:1} 4个被删,1为代表成功
// User.deleteMany({}).then(result => {
// console.log(result);
// });

//更新文档
//更新单个 第一个匹配到的
// User.updateOne({ 查询条件 }, { 要修改的值 }).then(result =>
// console.log(result)
// );//
// User.updateOne({ name: ‘李四’ }, { name: ‘李狗蛋’ }).then(result =>
// console.log(result)
// );
//更新多个
// User.updateMany({}, { password: ‘123456’ }).then(result => console.log(result));

//mongoose验证
// 在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
//required:true 必传字段

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农.one

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值