how to connect to mongoose and create a model code example
Example: how to connect to mongoose and create a model
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const PORT = process.env.PORT || 3000;
try {
mongoose.connect('mongodb://localhost/YOUR_DB_NAME', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}, () =>
console.log("connected"));
} catch (error) {
console.log("could not connect");
}
const Schema = mongoose.Schema
const BookSchema = new Schema({
name : String
})
const Model = mongoose.model
const Book = Model('Books',BookSchema)
const NodeJsGuide = new Book({name : 'NodeJS : A Guide' })
NodeJsGuide.save((err,result)=>{
if(err) console.log(err)
console.log(result);
})
app.get('/', (req, res) => {
res.send('check your browser console for any error , if no error you are good!');
});
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));