用猫鼬发送文档和子文档数据

时间:2020-07-24 05:33:51

标签: node.js mongodb express mongoose mongoose-schema

我正在尝试以json格式从文档和子文档中发送数据,以返回包含userID且可能不包含limit(要显示的子文档数),to(date)和from(date)的请求

我的模式

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

2 个答案:

答案 0 :(得分:1)

app = Flask(__name__)
app.config.from_object(Config)
app.config['TESTING'] = True
db = SQLAlchemy(app)
migrate = Migrate(app, db)

def make_celery(app):
    celery = Celery(
        app.import_name,
        backend=app.config['CELERY_RESULT_BACKEND'],
        broker=app.config['CELERY_BROKER_URL']
    )
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery


app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379',
    CELERY_RESULT_BACKEND='redis://localhost:6379'
)
celery = make_celery(app)

答案 1 :(得分:0)

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

  });