【问题标题】:How to find documents in array in mongoose如何在猫鼬的数组中查找文档
【发布时间】:2021-06-27 03:27:08
【问题描述】:

如何使用 mongoose.find() 方法找到以下代码。

Paid.find({info:{data:"status"}}) 这不起作用,因为它返回空数组

info{
  event: 'charge.success',
  data: {
    id: 1190118808,
    domain: 'test',
    status: 'success',
    reference: 'T458573232919212',
    amount: 100000,
    message: null,
    gateway_response: 'Successful',
    paid_at: '2021-06-26T00:25:33.000Z',
    created_at: '2021-06-26T00:25:24.000Z',
}

【问题讨论】:

标签: node.js mongodb express mongoose


【解决方案1】:

如果你使用猫鼬,它应该和YourModel.find({ data: { status: "success" } }) 一样简单,这是假设info 不是文档上的实际属性

完整示例(包括数据结构(Schema),简化):

const schema1 = new mongoose.Schema({ 
  data: {
    status: String
  }
});
const model1 = mongoose.model("model1", schema1);

(async () => {
  // connect the connection before this part
  await model1.create({ data: { status: "success" } });
  await model1.create({ data: { status: "failure" } });

  // this should only find & log the "success" one in the array
  const found = await model1.find({ data: { status: "success" } }).exec();
  console.log("found", found);
})()

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2020-07-25
    • 1970-01-01
    • 2014-02-17
    • 2014-02-03
    • 2016-11-04
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    相关资源
    最近更新 更多