node.js - 在猫鼬中发送文档和子文档数据
问题描述
我正在尝试以 json 格式从文档和子文档发送数据,以返回包含用户 ID 并且可能包含也可能不包含限制(要显示的子文档数量)、到(日期)和从(日期)的请求
我的架构
const logInfoSchema = new Schema(
{
description: { type: String, required: true, default: "" },
duration: { type: Number, required: true, default: 0 },
date: { type: String }
},
{ versionKey: false }
);
const userInfoSchema = new Schema(
{
username: { type: String, required: true, unique: true },
count: { type: Number, default: 0 },
log: [logInfoSchema]
},
{ versionKey: false }
);
当前代码,发送带有所有日志的数据
app.get("/api/exercise/log", (req, res) => {
const userId = req.query.userId;
console.log(userId);
if (!userId) {
res.send("enter user id");
} else {
userInfo.findById(userId, (err, data) => {
if (err) {
return err;
} else {
res.json(data);
}
});
}
});
解决方案
我们可以使用查询运算符来查找给定日期之间的日志,并使用limit
限制日期。结果。
app.get("/api/exercise/log", (req, res) => {
const userId = req.query.userId;
const from = req.query.from;
const to = req.query.to;
console.log(userId);
if (userId && from && to){
userInfo.find({_id:userId, "log.date": { "$gt": from, "$lt":to}},
{sort: {'date': -1}, limit: 20},(er,data) => {
if (err) {
return err;
}
else {
res.json(data);
}
});
}
else{
if (!userId) {
res.send("enter user id");
} else {
userInfo.findById(userId, (err, data) => {
if (err) {
return err;
} else {
res.json(data);
}
});
}
}
});
推荐阅读
- reactjs - Typescript - 它是什么类型的函数?
- mongodb - 从 mongo db 集合中删除重复记录
- nexus3 - 将常规文件上传到 Sonatype Nexus Repository Manager
- ios - 如何从通知响应中重新加载 iOS 14 小部件的时间线?
- xamarin.forms - Xamarin Forms:如何突出显示文本并暂停/播放文本到语音的音频?
- python - 将 5m OHLC 数据转换为 15m,Python
- python - 将循环神经网络部署到烧瓶 Web 服务
- apache-spark - AWS EMR 上的 1 个从节点未使用
- node.js - PayPal和转账到多个银行账户
- asp.net - 即使填充了文本字段,部分视图也会向模型发送空值