mongodb 和 mongoose 初探
发布日期:2025-04-14 14:26:26 浏览次数:7 分类:精选文章

本文共 1784 字,大约阅读时间需要 5 分钟。

MongoDB 开发指南

1. 安装 MongoDB

1.1 官方下载地址

请访问 MongoDB 官方网站下载最新版本。解压后的文件可以保存到任意路径。

1.2 环境配置

在 Windows 系统中:

  • 右键点击 "此电脑",选择 "属性"。
  • 点击 "高级系统设置"。
  • 选择 "环境变量"。
  • 在 "系统路径" 部分,点击 "编辑"。
  • 在 "路径" 字段中,输入 MongoDB 解压后的 bin 目录,点击 "确定"。
  • 1.3 版本检测

    在命令提示符中输入 mongod --version,若显示版本信息则安装成功。

    2. MongoDB 基本操作

    2.1 数据库管理

    • 启动数据库:在命令提示符中输入 mongod(默认数据存储目录为 data/db)。
    • 停止数据库:按下 Ctrl + C 或关闭命令窗口。

    2.2 数据库连接与退出

    • 连接数据库:打开新命令窗口,输入 mongo(默认连接本机数据库)。
    • 退出数据库:输入 exit 命令。

    2.3 常用命令

    • 查看数据库列表:输入 show dbs
    • 切换数据库:输入 use 数据库名
    • 创建集合:定义 Schema 并调用 save() 方法。

    3. 在 Node.js 中使用 MongoDB

    3.1 安装 Mongoose

    通过 npm 安装第三方包:

    npm install mongoose

    3.2 mongoose 示例代码

    const mongoose = require('mongoose');mongoose.connect('mongodb://localhost/test');const CatSchema = new mongoose.Schema({  name: String});const kitty = new Cat({ name: 'Zildjian' });kitty.save().then(() => console.log('数据已保存'));

    4. Mongoose 高级操作

    4.1 初始化数据库

    mongoose.connect('mongodb://localhost/mytest');const UserSchema = new mongoose.Schema({  username: { type: String, required: true },  password: { type: String, required: true },  email: { type: String }});const User = mongoose.model('User', UserSchema);

    4.2 增删改查

    • 添加数据:
    const admin = new User({  username: 'admin',  password: '123456',  email: 'admin@qq.com'});admin.save((err, ret) => {  if (err) {    console.log('保存失败');  } else {    console.log('保存成功', ret);  }});
    • 按条件查询:
    User.find({ username: 'zs' }, (err, ret) => {  if (err) {    console.log('查询失败');  } else {    console.log('查询结果', ret);  }});
    • 删除数据:
    User.remove({ username: 'admin' }, (err) => {  if (err) {    console.log('删除失败');  } else {    console.log('删除成功');  }});
    • 更新数据:
    User.findByIdAndUpdate('5bb87a44b70a9508346d35f9', { password: '123' }, (err, ret) => {  if (err) {    console.log('更新失败');  } else {    console.log('更新成功');  }});

    通过以上操作,可以轻松完成 MongoDB 的基础和高级操作。

    上一篇:mongodb 备份压缩_MongoDB实现备份压缩的方法教程 _ 蚂蚁视界
    下一篇:mongodb 命令行操作

    发表评论

    最新留言

    哈哈,博客排版真的漂亮呢~
    [***.90.31.176]2025年05月02日 16时41分50秒