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

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

展示所有产品.

显示单一产品.

未显示所有类别.

1.showing entire collection. enter image description here

2.showing single row of collection based on ID. enter image description here

3.showing collection of specific column. enter image description here

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}`);
})

推荐答案

您正在重叠获得这两条路由'/products/categories''/products/:_id'.

因此,在主路由'/products/categories'之前指定了URL参数为'/products/:_id'的路由,从而使其不可访问.

你有to move this route个:

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

before this one :

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

Node.js相关问答推荐

链接Inbox类方法,范围在哪里以及为什么发生变化?

CloudTasksClient在Firebase Function % s onDocumentCreated中实例化时导致错误

购物车是空的状态|本地存储不更新产品数量|Redux|

我的 React + Express 应用程序不断向我的数组添加一个空对象

将图像添加到多个产品的条带 checkout 会话中

当 Got 包因错误 JSON 崩溃时如何获取响应文本?

与诗乃一起嘲笑奈克斯

具有项目外部子路径导入的 Firebase 函数

如何为单个 mongo nodejs 驱动程序找到最佳连接池大小

npm chokidar 触发事件两次

AWS EC2 npm install 突然很慢

如何为一个网站实现这 2 个网址.即 www.administrator.sitename.com 和 www.sitename.com?

配额超出了每分钟的 Sheets API 写入请求数. node .js

node.js 中 res.setHeader 和 res.header 的区别

在 Node.js 与 Cron 作业(job)中设置间隔?

如何在 MongoDB 上只收听 localhost

如何使用 Node.js 在服务器端管理多个 JS 文件

我可以有条件地将 where() 子句添加到我的 knex 查询吗?

PhoneGap/Cordova Android 开发

我无法全局安装 nodemon,nodemon无法识别