0

I come from MySQL world so mongo queries are a bit difficult to make considering I can't really make sense of mongo style queries. I am trying to make a query for finding a string. The problem is from my very primitive knowledge about mongodb queries, the query I made isn't working. I tried it in mongoose as well in mongo shell.

Schema:

mongoose.Schema({
        doctorID : String,
        patientIDList : Array // array of strings
    });

Query Objective:

I want to find a doctor with doctorID and then look inside the patientIDList for an ID xxx. If the patientIDList doesn't contains xxx then add xxx in the list otherwise just add nothing.

Query:

The 2 queries I tried

MyModel.findOne({'doctorID':newAppointment.doctorID}, {'patientIDList' : newAppointment.patientID}, function(err){...});

MyModel.findOne({'doctorID': newAppointment.doctorID, 'patientIDList': newAppointment.patientID}, function(err){...});

What am I doing wrong? How can I make a query?

Shadow
  • 33,525
  • 10
  • 51
  • 64
user2498079
  • 2,872
  • 8
  • 32
  • 60

1 Answers1

0

It's always a bit of challenge to switch from a SQL to NoSQL DB and other way around. What you are trying to do is check if a value exists in an array. If the array is a string array you can simply query for the value in array.

MyModel.findOne({doctorID : newAppointment.doctorID}, {patientIDList :newAppointment.doctorID}, function(err, res){
    console.log(err, res);
})

Further read: https://docs.mongodb.com/manual/tutorial/query-documents/#match-an-array-element

Relevant Question: Find document with array that contains a specific value

Community
  • 1
  • 1
Vikram Tiwari
  • 3,615
  • 1
  • 29
  • 39