【问题标题】:retrieving data from database according to query conditions根据查询条件从数据库中检索数据
【发布时间】:2022-01-16 06:52:11
【问题描述】:
    "_id":{"$id":"61b5eb36029b48135465e766"},
"name":"push-ups","link":"https://google.com",
"image":"https://google.com",
"gender":["0","1","2"],
"goal":["lw","gw","sf"],
"age":60,
"excersietype":"chest",
"__v":0

这就是我的数据在数据库中的存储方式 我想根据3个条件获取数据

我从前面的性别目标和年龄得到 3 个查询,据此我必须检索数据

 const gender = req.query.gender;
    const age = req.query.age;
    const goal = req.query.goal
    const level = req.query.level

    if (level==='fb'){
        const getdata = new Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});
        console.log(getdata)
    }

这是查找数据的好方法吗,因为我遇到了错误

 UnhandledPromiseRejectionWarning: MongooseError: `Model.find()` cannot run without a model as `this`. Make sure you are not calling `new Model.find()`

我在获取时遇到错误

【问题讨论】:

  • 我解决了我没有使用 await 的错误。但在此之后我仍然没有收到任何数据

标签: javascript node.js mongodb express mongoose


【解决方案1】:

错误是明确的:Make sure you are not calling 'new Model.find()'。使用const getdata = Forbeg.find(...)

但是,您将立即遇到下一个问题,因为 Mongoose 模型返回 thenables(类似于 Promise)。 console.log(getdata) 将记录 Promise<pending>。您需要解决您的数据库调用,方法是

Forbeg.find(...).then( getdata => console.log(getData));

或者(更好!):

const getdata = await Forbeg.find(...);
console.log(getdata)

更好的是,添加.lean() 来获取简单的JSON 数据而不是Mongoose 对象数组(更快),并添加.exec() 来获取真正的Promise 而不是thenable:

const getdata = await Forbeg.find(...).lean().exec();
console.log(getdata)

【讨论】:

  • 我的查询在 find() 方法中是否正常,因为我没有得到任何数据@
  • 如果gendergoal 是数组,我认为查询是好的。你应该console.log它是肯定的。
  • 是的,谢谢它的工作
  • 很好,如果它解决了您的问题,请不要忘记将答案标记为已接受。
  • 你是说点赞?我现在不能这样做,因为我没有足够的声誉对不起,但我真的很感激谢谢你
【解决方案2】:

删除新运算符

const getData = Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 2021-07-25
    • 2021-01-20
    • 1970-01-01
    • 2022-12-18
    • 2014-04-16
    • 2017-01-15
    • 2012-03-08
    相关资源
    最近更新 更多