技术文摘
在 Mac 上为 Node.js 安装数据库
在 Mac 上为 Node.js 安装数据库
在 Mac 系统中为 Node.js 安装数据库,能极大地拓展应用程序的数据存储和管理能力。下面将详细介绍在 Mac 上为 Node.js 安装常用数据库的步骤。
安装 MongoDB
MongoDB 是一个流行的文档型数据库。打开终端,使用 Homebrew 包管理器来安装 MongoDB。在终端中输入:brew install mongodb-community。安装完成后,需要启动 MongoDB 服务。输入 brew services start mongodb-community 即可启动。
接着,在 Node.js 项目中使用 MongoDB,需要安装官方的 Node.js 驱动。进入项目目录,在终端输入 npm install mongodb 来安装驱动。在代码中引入驱动并连接数据库:
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("test");
const collection = database.collection("items");
// 进行数据操作
} finally {
await client.close();
}
}
run().catch(console.dir);
安装 MySQL
MySQL 是关系型数据库的代表。同样通过 Homebrew 安装,在终端输入 brew install mysql。安装完成后,启动 MySQL 服务:brew services start mysql。初次使用还需设置密码等配置。
在 Node.js 项目中使用 MySQL,先安装 mysql 模块:npm install mysql。以下是连接 MySQL 数据库的示例代码:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'yourpassword',
database: 'test'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
安装 PostgreSQL
PostgreSQL 也是一款强大的开源关系型数据库。通过 Homebrew 安装:brew install postgresql。启动服务:brew services start postgresql。
在 Node.js 项目里使用 PostgreSQL,安装 pg 模块:npm install pg。连接数据库示例:
const { Pool } = require('pg');
const pool = new Pool({
user: 'youruser',
host: 'localhost',
database: 'test',
password: 'yourpassword',
port: 5432,
});
pool.query('SELECT NOW()', (err, res) => {
console.log(err, res);
pool.end();
});
通过以上步骤,你可以在 Mac 上轻松为 Node.js 安装不同类型的数据库,并在项目中进行使用,根据实际需求构建强大的数据驱动应用程序。
- 前端开发必备!效率倍增的 Mock 神器安利
- Vue.js 设计与实现之十三:渲染器的核心功能 - 挂载与更新 02
- 不想敲代码,CTO职位更具吸引力
- Python Web3 开发:借助 Brownie 部署智能合约
- 业务视角下信息技术与业务的关系探讨
- 程序员转行运营之路:曾每日欲离职,终...
- JVM 参数指南:面向 Java 开发人员
- Python 中反转列表或数组的方法
- 全面解析推荐系统中的 debias
- 超越 Cat 的绝佳命令!
- GitHub API 下获取较大文件的方法
- 深度探究:Kafka 是否存在数据丢失问题
- DanceNN:字节自研的千亿级规模文件元数据存储系统介绍
- Pandas 中分类数据编码的十种方法
- 2024 年 Rust 能否封神?