-
-
Save heytulsiprasad/c1a222a83fbae0e71258a0e9b3b91fa9 to your computer and use it in GitHub Desktop.
Add mongoose to node and express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| MONGO_PROD_URI=mongodb+srv://admin:<password>@cluster.mongodb.net/<dbname>?retryWrites=true&w=majority | |
| MONGO_DEV_URI=mongodb://127.0.0.1:27017/<dbname> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require("dotenv").config() | |
| const express = require("express") | |
| const app = express() | |
| const mongoose = require("mongoose") | |
| mongoose | |
| .connect(process.env.MONGO_LOCAL_URI, { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true, | |
| useCreateIndex: true | |
| }) | |
| .then(() => console.log("Database connected!")) | |
| .catch((err) => console.log(err)) | |
| app.get("/", (req, res) => res.send("Server is up and running")) | |
| const UserSchema = new mongoose.Schema({ | |
| name: String, | |
| age: Number, | |
| isAdult: Boolean, | |
| joined: { | |
| type: Date, | |
| default: Date.now | |
| }, | |
| }) | |
| const User = mongoose.model("users", UserSchema) | |
| const newUser = new User({ | |
| name: "Elliot Alderson", | |
| age: 23, | |
| isAdult: true, | |
| }) | |
| newUser.save().then(() => console.log("Saved new user")) | |
| const PORT = process.env.PORT || 4444 | |
| app.listen(PORT, () => console.log(`Server is running on port ${PORT}`)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comment here, if you have any issues regarding the code part. Refer to the whole blog here.