在Ubuntu上使用Node.js集成数据库,你可以选择多种数据库,如MongoDB、MySQL、PostgreSQL等。以下是在Ubuntu上集成这些数据库的基本步骤:
sudo apt-get update
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
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
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
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项目中使用所选数据库进行开发了。