Find nested document referred by another ObjectId

49 views Asked by At

I have four different document which have same CId which is another id which represents all documents are subset of that ObjectId document.

Master

{ "_id" : ObjectId("582c5211c8a8e06c0849a238"), "name" : "MyName", "code" : "1234", "__v" : 0 }

Subsets

{ "_id" : ObjectId("584e72fc28a15d7c1ae0b3de"), "CId" : ObjectId("582c5211c8a8e06c0849a238"), "no_m" : 3, "create_date" : ISODate("2016-12-12T09:50:52.948Z"), "update_date" : ISODate("2016-12-19T14:22:28Z"), "__v" : 0}

{ "_id" : ObjectId("584e72fc28a15d7c1ae0b3df"), "CId" : ObjectId("582c5211c8a8e06c0849a238"), "no_m" : 3, "create_date" : ISODate("2016-12-12T09:50:52.948Z"), "update_date" : ISODate("2016-12-19T14:22:28Z"), "__v" : 0}

{ "_id" : ObjectId("584e72fc28a15d7c1ae0b3dg"), "CId" : ObjectId("582c5211c8a8e06c0849a238"), "no_m" : 3, "create_date" : ISODate("2016-12-12T09:50:52.948Z"), "update_date" : ISODate("2016-12-19T14:22:28Z"), "__v" : 0}

{ "_id" : ObjectId("584e72fc28a15d7c1ae0b3dh"), "CId" : ObjectId("582c5211c8a8e06c0849a238"), "no_m" : 3, "create_date" : ISODate("2016-12-12T09:50:52.948Z"), "update_date" : ISODate("2016-12-19T14:22:28Z"), "__v" : 0}

I want to find all documets using monoose in Node.js

My code is

var c = 582c5211c8a8e06c0849a238
SubsetSchema.find({'CId' : cid},function(err,Docs){
     if (err)
     {   
         console.log(err);
         return res.status(400).send({"err":err});
     }
     });
     console.log(Docs);

But it gives me error

How can I include ObjectId in mongoose find()

with mongodb db.Docs.find({"CId":ObjectId("582c5211c8a8e06c0849a238")}) working properly

1

There are 1 answers

1
Basim Hennawi On BEST ANSWER

No need to cast or use the ObjectId constructor here, just pass it as string but also the error you got maybe due to some syntax error, you need to adjust your code to be as follow:

var cid = '582c5211c8a8e06c0849a238';
SubsetSchema.find({'CId' : cid},function(err, Docs) {
  if (err)
  {   
     console.log(err);
     return res.status(400).send({"err":err});
  }
  console.log(Docs);
});

First: Define the variable properly to match where it use c to cid.

Second: Assign it as string by wrap it with single/double quotes.

Third: Get the console.log statement inside the callback function where Docs is defined.