博客
关于我
mongodb 和 mongoose 初探
阅读量:794 次
发布时间:2023-02-09

本文共 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 的基础和高级操作。

    转载地址:http://xcffk.baihongyu.com/

    你可能感兴趣的文章
    Mac下忘记MySQL密码可以这样做!
    查看>>
    Mac下配置多个SSH-Key (gitLab)
    查看>>
    Mac安装Maven
    查看>>
    Mac实现远程服务器登录管理
    查看>>
    mac常用命令
    查看>>
    mac更新后 homestead 无法使用
    查看>>
    mac环境安装docker
    查看>>
    MAC生成公钥私钥、PKCS1 转 PKCS8
    查看>>
    Mac电脑怎么读写不了移动硬盘?解决苹果电脑不能读写移动硬盘问题
    查看>>
    Mac电脑生成git的公私钥(拉取代码更便捷)
    查看>>
    magento1给customer添加自定义属性
    查看>>
    Magic Leap是快出产品的节奏,已开放内容开发者注册通道
    查看>>
    Majorization-Minimization (MM) 和 Successive Convex Approximation (SCA)
    查看>>
    makefile 打印
    查看>>
    makefile工作笔记0001---认识使用makefile
    查看>>
    Makefile遗漏分隔符错误解决
    查看>>
    malloc和定位new表达式
    查看>>
    MAMP无法正常启动,错误提示The built-in Apache is active
    查看>>
    Managing CentOS/RHEL kernel modules.
    查看>>
    Mangoa-Auth/芒果自助多应用企业级授权系统拥有盗版入库、远程更新等功能
    查看>>