📅  最后修改于: 2022-03-11 15:02:45.678000             🧑  作者: Mango
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}`));