2022-08-11 12:30:04 +01:00
|
|
|
---
|
2024-06-15 11:00:03 +01:00
|
|
|
tags:
|
|
|
|
- mongo-db
|
|
|
|
- node-js
|
|
|
|
- mongoose
|
|
|
|
- databases
|
2022-08-11 12:30:04 +01:00
|
|
|
---
|
|
|
|
|
|
|
|
# Connect to a database with Mongoose
|
|
|
|
|
2024-02-02 15:58:13 +00:00
|
|
|
Now that we have installed and configured MongoDB, we need to connect to it via
|
|
|
|
Node.js. Mongoose is a simple API for interacting with a Mongo database via
|
|
|
|
Node.
|
2022-08-11 12:30:04 +01:00
|
|
|
|
2024-02-02 15:58:13 +00:00
|
|
|
With Mongoose installed we can connect to a database. We don't have any Mongo
|
|
|
|
databases yet beyond the defaults but the following Mongoose connection logic
|
|
|
|
will create and connect to a new database called `playground`:
|
2022-08-11 12:30:04 +01:00
|
|
|
|
2024-02-02 15:58:13 +00:00
|
|
|
Providing the Mongo server is running (execture `mongod`), we will see the
|
|
|
|
confirmation message in the console.
|
2022-08-11 12:30:04 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
mongoose
|
2024-02-02 15:58:13 +00:00
|
|
|
.connect("mongodb://127.0.0.1/playground")
|
|
|
|
.then(() => console.log("Connected to MongoDB"))
|
2022-08-11 12:30:04 +01:00
|
|
|
.catch((err) => console.error(err));
|
|
|
|
```
|