首页 > 解决方案 > 在猫鼬中发送文档和子文档数据

问题描述

我正在尝试以 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);
      }
    });
  }
});

标签: node.jsmongodbexpressmongoosemongoose-schema

解决方案


我们可以使用查询运算符来查找给定日期之间的日志,并使用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);
            }
          });
        }
      }

  });

推荐阅读