how to connect to mongoose and create a model

Solutions on MaxInterview for how to connect to mongoose and create a model by the best coders in the world

showing results for - "how to connect to mongoose and create a model"
Josué
27 Jan 2020
1const express = require('express');
2const app = express();
3const mongoose = require('mongoose');
4const bodyParser = require('body-parser');
5
6
7
8
9app.use(bodyParser.json());
10const PORT = process.env.PORT || 3000;
11
12//connecting to db
13try {
14    mongoose.connect('mongodb://localhost/YOUR_DB_NAME', {
15        useNewUrlParser: true,
16        useUnifiedTopology: true,
17      	useCreateIndex: true,
18      }, () =>
19      console.log("connected"));
20  } catch (error) {
21    console.log("could not connect");
22  }
23
24
25
26//creating a schema
27const Schema = mongoose.Schema
28const BookSchema = new Schema({
29name : String
30})
31
32
33//creating a schema
34const BookSchema = mongoose.Schema({
35  title: {
36    type: String,
37    required: true,
38  },
39  price: {
40    type: Number,
41  },
42});
43
44//creating a model
45const Model = mongoose.model;
46const Book = Model("Books", BookSchema);
47
48//database already loaded with sample data 
49//ROUTES to get books
50app.get("/books", async (req, res) => {
51  try {
52    const book = await Book.find({});
53    res.json({ success: true, book });
54  } catch (error) {
55    res.json({ success: false, msg: "failed to fetch book" });
56  }
57});
58
59
60 app.get('/', (req, res) => {
61 	res.send('check your browser console for any error , if no error you are good!');
62 	
63  });
64
65app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
similar questions