node连接MongnDB以及MongnDB的增删改查(一个案例)

1.node连接MongoDB

const mongoose = require('mongoose');

//链接服务器
//本地服务器名称中不能有空字符串,比如:'playground  '
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log("数据库连接成功!"))
    .catch(err => console.log("数据库链接失败!!!!", err))

2.增删改查

2.1创建集合

const mongoose = require('mongoose');

//链接服务器
//本地服务器名称中不能有空字符串,比如:'playground  '
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log("数据库连接成功!"))
    .catch(err => console.log("数据库链接失败!!!!", err))

//创建集合规则
const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    isPublish: Boolean
});


//使用规则创建集合
//Course为定义的集合名字,但是在数据库中实际创建的数据库名字是:courses
const Course = mongoose.model('Course', courseSchema);

//创建实例
const course = new Course({
    name: 'ndejs基础',
    author: 'pink',
    isPublish: true
});
//将数据插入到数据库当中
course.save();

 

法二:

const mongoose = require('mongoose');

//链接服务器
//本地服务器名称中不能有空字符串,比如:'playground  '
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log("数据库连接成功!"))
    .catch(err => console.log("数据库链接失败!!!!", err))

//创建集合规则
const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    isPublish: Boolean
});


//使用规则创建集合
//Course为定义的集合名字,但是在数据库中实际创建的数据库名字是:courses
const Course = mongoose.model('Course', courseSchema);

//向集合插入文档
// Course.create({ name: 'JS', author: 'pink老师', isPublish: false }, (err, result) => {
//     console.log(err);
//     console.log(result);
// })

//向集合插入文档,使用promise()方法
Course.create({ name: 'css', author: 'k老师', isPublish: true })
    .then((result) => {
        console.log(result);
    })

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

// 创建集合规则
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
    password: String,
    hobbies: [String]
});

// 使用规则创建集合
const User = mongoose.model('User', userSchema);

// 查询用户集合中的所有文档
// User.find().then(result => console.log(result));
// 通过_id字段查找文档,find返回的是一个数组,可以是一个或者多个文档
// User.find({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result))

// findOne方法返回一条文档 默认返回当前集合中的第一条文档,返回的是对象不是数组
// User.findOne({ name: '李四' }).then(result => console.log(result))


// 查询用户集合中年龄字段大于20并且小于40的文档
// User.find({ age: { $gt: 20, $lt: 40 } }).then(result => console.log(result))
// 查询用户集合中hobbies字段值包含足球的文档
// User.find({ hobbies: { $in: ['足球'] } }).then(result => console.log(result))

// 选择要查询的字段,-_id表示不想查询id字段
// User.find().select('name email -_id').then(result => console.log(result))
// 根据年龄字段进行升序排列
// User.find().sort('age').then(result => console.log(result))
// 根据年龄字段进行降序排列
// User.find().sort('-age').then(result => console.log(result))
// 查询文档跳过前两条结果 限制显示3条结果
// User.find().skip(2).limit(3).then(result => console.log(result))

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

// 创建集合规则
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
    password: String,
    hobbies: [String]
});

// 使用规则创建集合
const User = mongoose.model('User', userSchema);
//findOneAndDelete():查找一条文档并且删除,返回的是 删除的文档;
//如果查询条件匹配了多个文档,那么将会删除第一个匹配的文档
// User.findOneAndDelete({ _id: '5c09f267aeb04b22f8460968' }, { useUnifiedTopology: true }).then(result => console.log(result));

//删除多条文档
User.deleteMany({}).then(result => console.log(result))

 

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

// 创建集合规则
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
    password: String,
    hobbies: [String]
});

// 使用规则创建集合
const User = mongoose.model('User', userSchema);

//更新集合中文档(更新一个,匹配到多个时只更新第一个文档)
User.updateOne({ name: '李四' }, { name: '李狗蛋' }).then(result => { console.log(result) });
//更新集合中文档(更新多个)
User.updateMany({}, { age: 120 }).then(result => console.log(result))

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    // 连接成功
    .then(() => console.log('数据库连接成功'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败'));
//创建集合的规则 (mongoose提供的一些验证规则)
const postSchema = new mongoose.Schema({
    title: {
        type: String,
        //必选字段
        required: [true, '请传入文章标题'],
        //字段的最值区间
        minlength: [2, '文章长度大于等于2'],
        maxlength: [5, '文章长度小于等于5'],
        //去除字符串两边的空格
        trim: true
    },
    age: {
        type: Number,
        //数字的最小范围
        min: [18, ">=18"],
        //数字的最大范围
        max: 100
    },
    publishDate: {
        type: Date,
        //如果没有传入日期,则使用默认日期
        default: Date.now
    },
    category: {
        type: String,
        //列举出当前字段可以拥有的值
        enum: {
            values: ['html', 'css', 'javascript'],
            message: "输入文件类型错误"
        },

    },
    //自定义验证规则
    author: {
        type: String,
        validate: {
            validator: (v) => {
                //返回布尔值,true表示验证成功
                //v :要验证的值
                return v && v.length > 4
            },
            //自定义错误信息
            message: '不符合规则'
        }
    }
});
//创建集合 post
const post = mongoose.model('Post', postSchema);
//为集合插入数据
post.create({ title: "  qqq00 ", age: 25, category: 'java', author: '5675' })
    .then(result => console.log(result))
    .catch(error => {
        //获取错误对象信息
        const err = error.errors;

        //循环错误对象信息
        for (var attr in err) {
            //打印
            console.log(err[attr]["message"]);
        }
    })

 

 

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

// 用户集合规则
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    }
});
// 文章集合规则
const postSchema = new mongoose.Schema({
    title: {
        type: String
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
});
// 用户集合
const User = mongoose.model('User', userSchema);
// 文章集合
const Post = mongoose.model('Post', postSchema);

// 创建用户
User.create({ name: 'itheima' }).then(result => console.log(result));
// 创建文章
Post.create({ titile: '123', author: '5c0caae2c4e4081c28439791' }).then(result => console.log(result));
//查询关联的集合信息
Post.find().populate('author').then(result => console.log(result))

1.搭建网站服务器,实现客户端与服务器端的通信

2.连接数据库(借助第三方模块mongoose连接数据库),创建用户集合,向集合中插入文档

      2.1连接数据库(借助第三方模块mongoose连接数据库)

2.2创建用户集合

第一步需要先创建集合规则:

 第二步利用集合规则创建 集合:

为users集合导入数据(将user.josn文件里面的数据导入集合):

3.当用户访问/list时,将所有用户信息查询出来

3.1实现路由功能(先获取用户的请求方式以及请求地址,然后对请求方式与请求地址进行判断即可实现路由功能)

req.url是带有get请求方式的地址也就是说它不是一个纯粹的请求地址,可用系统模块下面的url.parsh()方法对请求地址进行处理

(parse()方法返回一个对象,返回对象里面有一个pathname,pathname就是纯粹的请求地址)

 3.2呈现用户页面(可以先将页面存在一个变量list中,然后再变量响应给客户端)

 3.3从数据库中查询用户信息,将用户信息展示在列表中

4 .当用户访问/add时,呈现表单页面,并实现添加用户信息功能

4.1添加/add路由

4.2实现添加用户信息功能

 

 

5.当用户访问/modify时,呈现修改页面,并实现修改用户信息功能

修改用户信息分为两大步 (5.1  \ 5.2)

5.1增加页面路由,呈现页面(1.在点击修改按钮时候,将用户Id传递到当前页面2.从数据库中查询当前用户信息,将信息展示在页面中)

 

5.2.实现用户修改功能(1.指定表单提交地址以及请求方式 2.接受客户端传递过来的修改信息,找到用户,将用户信息修改为最新的)

 

6 .当用户访问/delete时,实现用户删除功能

当用户点击删除按钮时,向服务器发送一个请求, 并将当前用户的id作为参数通过get方式 传递给服务器端。服务器要为当前请求创建一个路由,在此路由中要接收到用户传递过来的id参数,然后根据这个id在数据库中找到数据并且删除。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

1planet

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

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

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

打赏作者

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

抵扣说明:

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

余额充值