【发布时间】:2020-07-24 17:50:54
【问题描述】:
我正在尝试以 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);
}
});
}
});
【问题讨论】:
-
你能显示请求的网址吗?
-
/api/exercise/log?userId=5f1a48d64c7a1230d91d129c但可以像/api/exercise/log?userId=333&from=2019-3-13&to=2020-3-13&limit=5@prax -
通过日志我的意思是日志数组中的所有元素(见架构)
{"count":11,"_id":"5f1a48d64c7a1230d91d129c","username":"xrahulx","log":[{"description":"fff","duration":3,"_id":"5f1a48df4c7a1230d91d129d","date":"Fri May 10 2019"},{"description":"hhh","duration":3,"_id":"5f1a4a5bdfd648354d80d804","date":"Fri Jul 24 2020"},{"description":"hh","duration":3,"_id":"5f1a4ad52547f937215c529a","date":"Fri Jul 24 2020"},{"description":"log","duration":3,"_id":"5f1a4b4f7163d9383ef52f85","date":"Fri Jul 24 2020"},{"description":"log","duration":3,"_id":"5f1a4b73b9cc9038873b129f","date":"Fri Jul 24 2020"}]} -
但我还需要限制从 log 返回的元素数量,使用限制变量(如果存在)并且它不需要 to 和 from 存在
-
这对您有帮助吗:
db.test.find({_id:userId, "log.date": { "$gt": from, "$lt": to}},callback)
标签: node.js mongodb express mongoose mongoose-schema