Answers for "how to connect to mongoose and create a model"

0

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;

//connecting to db
try {
    mongoose.connect('mongodb://localhost/YOUR_DB_NAME', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      	useCreateIndex: true,
      }, () =>
      console.log("connected"));
  } catch (error) {
    console.log("could not connect");
  }



//creating a schema
const Schema = mongoose.Schema
const BookSchema = new Schema({
name : String
})


//creating a schema
const BookSchema = mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
  },
});

//creating a model
const Model = mongoose.model;
const Book = Model("Books", BookSchema);

//database already loaded with sample data 
//ROUTES to get books
app.get("/books", async (req, res) => {
  try {
    const book = await Book.find({});
    res.json({ success: true, book });
  } catch (error) {
    res.json({ success: false, msg: "failed to fetch book" });
  }
});


 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}`));
Posted by: Guest on December-19-2020

Code answers related to "how to connect to mongoose and create a model"

Code answers related to "Javascript"

Browse Popular Code Answers by Language