如何使用 Node.js、Express 和 Mongoose 创建多个 API

问题描述 投票:0回答:1

我正在尝试使用模式模式在node.js 中创建多个express API。如果我创建两个以上的 API,那么第三个(最后一个)就不起作用,我面临的问题是。

正如您在下面的屏幕截图中看到的。 3号。

显示所有产品。

显示单品。

未显示所有类别。

1.显示整个系列。

2.根据ID显示单行集合。

3.显示特定列的集合。

这是模块架构:

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

这里是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}`);
})
node.js express mongoose mongoose-schema
1个回答
0
投票

当你点击这个网址时

'/products/categories'
实际上你正在点击这条路线
'/products/:_id'
。 你必须移动这条路线

//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))
})

在此之前:

//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))
})
© www.soinside.com 2019 - 2024. All rights reserved.