Home > Mobile >  MongoDB How to define a query for find an object in array, but the array exist of Object references
MongoDB How to define a query for find an object in array, but the array exist of Object references

Time:03-31

Basically what I want to do is that I have an ObjectId of a qr. I want to use that ObjectId to find out which qrBlock does it belong. Im leaving my dbmodel here so you can track easily.

qrRoute.post("/scanQr", (req, res) => {
  let { data } = req.body;
  var id = mongoose.Types.ObjectId(data);
  Qr.findById(id)
    .exec()
    .then((qrr) => {
      QrBlock.find({ qr: { "qr.$": id } }, (qrblck) => {
        console.log(qrblck);
      });

      
    });
});

I tried this code above it didn't work.

CodePudding user response:

did you try this way

qrRoute.post("/scanQr", (req, res) => {
  let { data } = req.body;
  var id = mongoose.Types.ObjectId(data);
  Qr.findById(id)
    .exec()
    .then((qrr) => {
      QrBlock.find({ qr: id }, (qrblck) => {
        console.log(qrblck);
      });

      
    });
});

CodePudding user response:

QrBlock.findOne({ qr: { $all: [qrr._id] } })

this worked for me

  • Related