ubuntu

Node.js在Ubuntu上如何集成数据库

小樊
43
2025-07-21 22:21:06
栏目: 编程语言

在Ubuntu上使用Node.js集成数据库,你可以选择多种数据库,如MongoDB、MySQL、PostgreSQL等。以下是在Ubuntu上集成这些数据库的基本步骤:

  1. 更新系统软件包列表:
sudo apt-get update
  1. 安装Node.js:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
  1. 安装数据库软件包:
sudo apt-get install -y mongodb
sudo systemctl start mongod
sudo systemctl enable mongod
sudo apt-get install -y mysql-server
sudo mysql_secure_installation
sudo apt-get install -y postgresql postgresql-contrib
sudo systemctl start postgresql
sudo systemctl enable postgresql
  1. 创建数据库和用户:
mongo
use myDatabase
db.createUser({ user: "myUser", pwd: "myPassword", roles: [{ role: "readWrite", db: "myDatabase" }] })
exit
mysql -u root -p
CREATE DATABASE myDatabase;
CREATE USER 'myUser'@'localhost' IDENTIFIED BY 'myPassword';
GRANT ALL PRIVILEGES ON myDatabase.* TO 'myUser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
sudo -u postgres psql
CREATE DATABASE myDatabase;
CREATE USER myUser WITH ENCRYPTED PASSWORD 'myPassword';
GRANT ALL PRIVILEGES ON DATABASE myDatabase TO myUser;
\q
  1. 在Node.js项目中使用数据库:
npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://myUser:myPassword@localhost:27017/myDatabase', { useNewUrlParser: true, useUnifiedTopology: true });
npm install mysql
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'myUser',
  password: 'myPassword',
  database: 'myDatabase'
});
connection.connect();
npm install pg
const { Client } = require('pg');
const client = new Client({
  host: 'localhost',
  user: 'myUser',
  password: 'myPassword',
  database: 'myDatabase'
});
client.connect();

现在你可以在Node.js项目中使用所选数据库进行开发了。

0
看了该问题的人还看了