Skip to content

Instantly share code, notes, and snippets.

@LingleDev
Created May 9, 2019 18:24
Show Gist options
  • Save LingleDev/7262f03c7d46522d84aa9ca8d0cadf43 to your computer and use it in GitHub Desktop.
Save LingleDev/7262f03c7d46522d84aa9ca8d0cadf43 to your computer and use it in GitHub Desktop.
How to Connect, Read, and Write to a MongoDB Atlas Database with Mongoose
// run 'npm i -s mongoose'
const mongoose = require('mongoose')
// connect
mongoose.connect(`your-auth-url-here`)
.then(() => console.log("Mongoose has connected."))
.catch(err => console.log(`Mongoose failed to connect. Error: ${err}`))
// make a new schema
const schema = mongoose.Schema({
// this is just an example, you don't have to use these specific details
// key: value - this can be set/read just like objects.
username: String,
password: String,
email: String,
zip_code: String
})
// save the schema to MongoDB
mongoose.model("accountExample", schema)
// to get that schema, use
const account = mongoose.model('accountExample')
// to create a new entry in the 'accountExample' database,
const newAccount = new account({
username: "FHGDev",
password: "nope",
email: "fhgdev@gmail.com",
zip_code: "12345"
})
// save it to the database
newAccount.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment