我正在try 使用模式模式在node.js中创建多个Express API.我面临的问题是,如果我创建两个以上的API,那么第三个(最后一个)就不起作用了.
正如您在下面的屏幕截图中所看到的.3号.
展示所有产品.
显示单一产品.
未显示所有类别.
2.showing single row of collection based on ID.
3.showing collection of specific column.
here is module schema:
const mongoose = require('mongoose');
const ProductSchema = new mongoose.Schema({
title: String,
description: String,
category: String,
})
const PostModel = mongoose.model("products", ProductSchema) //"table name", UserSchema
module.exports = PostModel
here is index.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
//export module schema
const PostModel = require('./models/CreatePost')
// Middleware
const app = express()
app.use(cors());
app.use(express.json());
//define port
const port = 5000;
//define database
mongoose.connect("mongodb+srv://username:<password>@cluster0.jvxew8i.mongodb.net/store")
//find by table ID
app.get('/products/:_id', function(req, res) {
PostModel.findById(req.params._id)
.then(products => res.json(products))
.catch(err => res.json(err))
})
//find by table
app.get('/products', function(req, res) {
PostModel.find()
.then(products => res.json(products))
.catch(err => res.json(err))
})
//find by specific column
app.get('/products/categories', function(req, res) {
PostModel.find({}, {category: 1, _id: 0})
.then(products => res.json(products))
.catch(err => res.json(err))
})
// Server listen
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
})