Search code examples
node.jsmongodbexpressmongoosemongoose-schema

send document and subdocument data in mongoose


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

Solution

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