如何在猫鼬的数组中查找文档

时间:2021-06-26 00:44:21

标签: node.js mongodb express mongoose

我如何使用 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',
}

1 个答案:

答案 0 :(得分:0)

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

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

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