如何在 Node.js 中限制 MongoDB 请求中的文档数量?
假设您正在开发一个测验 API,网络上的任何人都可以使用它根据定义的类别获取随机问题。您已经完成了 API 并且它已经通过了所有测试参数,现在为了用户,您想要添加一个功能,让用户决定他们想要解决多少问题,并且您的 API 将为他们提供这么多问题。这里是有用的 mongo 功能限制。
参考 mongo 文档,limit 可以理解为一个选项,它限制了必须传递到下一个管道进行处理的文档数量。
句法:
{ $limit: }
对于 Node.js,我们将为此特定目的使用mongoose 。假设您为内容管理系统创建了 Post 模型,让我们尝试使用 find() 方法获取一定数量的帖子。
Javascript
Post.find().limit(5).then(posts=>{
if(!posts){
const error=new Error("No post is there to fetch");
error.statusCode=404;
throw(error);
}
return res.status(200).json({post:posts});
}).catch(err=>console.log(err));
Javascript
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
// For processing application/json
app.use(bodyParser.json());
// Setting up CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "*");
next();
});
app.get("/test", (req, res, next) => {
res.send("working
");
});
mongoose
.connect("mongodb://localhost:27017/articleDB")
.then(app.listen(8000, () => console.log("listening at port 8000")));
Javascript
// Requiring mongoose
const mongoose = require("mongoose");
// Schema of our post model
const postSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
},
{ timestamps: true }
);
// Model
const Post = mongoose.model("Post", postSchema);
Javascript
// POST http://localhost:8000/post
app.post("/post",(req,res,next)=>{
const newPost = new Post({
title: req.body.title,
content: req.body.content,
});
newPost
.save()
.then((post) => {
return res.status(201).json({ post: post });
})
.catch((err) => {
res.status(500).json({error:err});
});
})
Javascript
// GET http://localhost:8000/posts
app.get("/posts",(req,res,next)=>{
const requestCount = req.query.count;
Post.find()
.countDocuments()
.then((count) => {
// if requested count is more than actual count of posts in database
if (requestCount > count) {
const error = new Error("invalid request in quantity");
error.statusCode = 400;
throw error;
}
//returning posts while limiting the count
return Post.find().limit(Number(requestCount));
})
.then((posts) => {
res.status(200).json({ posts: posts });
})
.catch((err) => {
const status=error.statusCode || 500;
res.status(status).json({error:err});
});
})
Javascript
const express = require("express");
const bodyParser = require("body-parser");
// Requiring mongoose for interacting with mongoDB database
const mongoose = require("mongoose");
const app = express();
// For processing application/json
app.use(bodyParser.json());
// Setting up CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "*");
next();
});
//---- mongo collection setup ----
// schema of our post model
const postSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
},
{ timestamps: true }
);
// model
const Post = mongoose.model("Post", postSchema);
//for testing purpose - can ignore it
app.get("/test", (req, res, next) => {
res.send("working
");
});
//-----apis----------
// POST http://localhost:8000/post
app.post("/post", (req, res, next) => {
const newPost = new Post({
title: req.body.title,
content: req.body.content,
});
newPost
.save()
.then((post) => {
return res.status(201).json({ post: post });
})
.catch((err) => {
res.status(500).json({ error: err });
});
});
// GET http://localhost:8000/posts
app.get("/posts", (req, res, next) => {
const requestCount = req.query.count;
Post.find()
.countDocuments()
.then((count) => {
// if requested count is more than actual
// count of posts in database
if (requestCount > count) {
const error = new Error("invalid request in quantity");
error.statusCode = 400;
throw error;
}
// returning posts while limiting the count
return Post.find().limit(Number(requestCount));
})
.then((posts) => {
res.status(200).json({ posts: posts });
})
.catch((err) => {
const status = err.statusCode || 500;
res.status(status).json({ error: err });
});
});
// connecting to database and serving up server
mongoose
.connect("mongodb://localhost:27017/articleDB")
.then(app.listen(8000, () => console.log("listening at port 8000")));
将要获取的文档数量作为参数传递给限制。这是一个相当抽象的权利?不用担心,让我们从一开始就完成整个过程。
假设 Node JS、express 和mongoose的基础不错。从根据定义的限制创建帖子和获取帖子开始。
后续工作流程将是:
- 设置环境
- 使用mongoose创建 Post 模式
- 开发用于创建帖子的 API
- 开发用于从数据库中获取指定数量的帖子的 API
配置:
锅炉板:
touch app.js
设置 NPM 设置:
npm init
安装依赖项:
npm i express body-parser mongoose
项目结构:现在,您的文件树看起来会有所不同。
按照以下步骤一一实现目标:
第 1 步:设置 app.js。
文件名:app.js
Javascript
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
// For processing application/json
app.use(bodyParser.json());
// Setting up CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "*");
next();
});
app.get("/test", (req, res, next) => {
res.send("working
");
});
mongoose
.connect("mongodb://localhost:27017/articleDB")
.then(app.listen(8000, () => console.log("listening at port 8000")));
运行 app.js 文件
node .\app.js
输出:现在点击 localhost:8000/test,你应该期待。
现在,当我们完成基本的应用程序设置后,让我们创建所需的 API。
创建 Post Schema:可以使用mongoose在 Node 中轻松创建模式。
Javascript
// Requiring mongoose
const mongoose = require("mongoose");
// Schema of our post model
const postSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
},
{ timestamps: true }
);
// Model
const Post = mongoose.model("Post", postSchema);
用于创建帖子的 API:现在,当我们完成创建模型和模式后,我们将继续创建我们的第一个 API,然后使用 Postman 对其进行测试。
Javascript
// POST http://localhost:8000/post
app.post("/post",(req,res,next)=>{
const newPost = new Post({
title: req.body.title,
content: req.body.content,
});
newPost
.save()
.then((post) => {
return res.status(201).json({ post: post });
})
.catch((err) => {
res.status(500).json({error:err});
});
})
URL - http://localhost:8000/post
Method - POST
Content-Type - application/json
Body of the request should contain -
i. title - title of your article
ii. content - content of your article
输出:
根据查询的帖子数获取帖子的 API:想法是将计数作为查询传递到 API 端点,然后使用基本验证和限制处理该查询。
Javascript
// GET http://localhost:8000/posts
app.get("/posts",(req,res,next)=>{
const requestCount = req.query.count;
Post.find()
.countDocuments()
.then((count) => {
// if requested count is more than actual count of posts in database
if (requestCount > count) {
const error = new Error("invalid request in quantity");
error.statusCode = 400;
throw error;
}
//returning posts while limiting the count
return Post.find().limit(Number(requestCount));
})
.then((posts) => {
res.status(200).json({ posts: posts });
})
.catch((err) => {
const status=error.statusCode || 500;
res.status(status).json({error:err});
});
})
limits只接受一个数字作为参数,但默认查询参数是字符串类型,这需要我们将其类型转换为数字。
Post.find().countDocuments()返回该特定集合下存在的文档总数。
URL - http://localhost:8000/posts/?count={limit}
Method - GET
Example Request - http://localhost:8000/posts/?count=4
输出:
最终解决方案:
文件名:app.js
Javascript
const express = require("express");
const bodyParser = require("body-parser");
// Requiring mongoose for interacting with mongoDB database
const mongoose = require("mongoose");
const app = express();
// For processing application/json
app.use(bodyParser.json());
// Setting up CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "*");
next();
});
//---- mongo collection setup ----
// schema of our post model
const postSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
},
{ timestamps: true }
);
// model
const Post = mongoose.model("Post", postSchema);
//for testing purpose - can ignore it
app.get("/test", (req, res, next) => {
res.send("working
");
});
//-----apis----------
// POST http://localhost:8000/post
app.post("/post", (req, res, next) => {
const newPost = new Post({
title: req.body.title,
content: req.body.content,
});
newPost
.save()
.then((post) => {
return res.status(201).json({ post: post });
})
.catch((err) => {
res.status(500).json({ error: err });
});
});
// GET http://localhost:8000/posts
app.get("/posts", (req, res, next) => {
const requestCount = req.query.count;
Post.find()
.countDocuments()
.then((count) => {
// if requested count is more than actual
// count of posts in database
if (requestCount > count) {
const error = new Error("invalid request in quantity");
error.statusCode = 400;
throw error;
}
// returning posts while limiting the count
return Post.find().limit(Number(requestCount));
})
.then((posts) => {
res.status(200).json({ posts: posts });
})
.catch((err) => {
const status = err.statusCode || 500;
res.status(status).json({ error: err });
});
});
// connecting to database and serving up server
mongoose
.connect("mongodb://localhost:27017/articleDB")
.then(app.listen(8000, () => console.log("listening at port 8000")));
输出:数据库,现在我们有了启用文档限制功能的简单 API。