I'm trying to send data from document and subdocument in json format,in return of request which contains userID and may or may not contain limit(number of sub docs to show), to(date) and from(date)
my schema
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 }
);
current code, sends data with all log
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);
}
});
}
});
We can use query operators to find logs beetween given dates and use the limit
to limit the no. of results.
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);
}
});
}
}
});
let logProcessing = (log, to, from, limit) => {
if (limit < 0) {
limit = 0;
}
if (dateValidator(to) && dateValidator(from)) {
return log
.filter(
date => new Date(date["date"]) >= from && new Date(date["date"]) <= to
)
.slice(0, limit);
} else if (dateValidator(from)) {
return log.filter(date => new Date(date["date"]) >= from).slice(0, limit);
} else if (dateValidator(to)) {
return log.filter(date => new Date(date["date"]) <= to).slice(0, limit);
} else {
return log.slice(0, limit);
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.