Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Last active September 20, 2020 16:26
Show Gist options
  • Select an option

  • Save heytulsiprasad/c1a222a83fbae0e71258a0e9b3b91fa9 to your computer and use it in GitHub Desktop.

Select an option

Save heytulsiprasad/c1a222a83fbae0e71258a0e9b3b91fa9 to your computer and use it in GitHub Desktop.
Add mongoose to node and express
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>
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}`))
@heytulsiprasad
Copy link
Copy Markdown
Author

heytulsiprasad commented Sep 20, 2020

Comment here, if you have any issues regarding the code part. Refer to the whole blog here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment