title: How serialize MongoDb ObjectId("uniqueid") to JSON in nodejs?
body: <p>Let's assume we have a query builder service B that spits out mongo db query when called. This query is received by service A and it executes it as is with mongo db official nodejs driver.</p>
  <p>How do I send something like :</p>
  <pre><code>[{
    _id: new mongo.ObjectID(&quot;5f3258cfbaaccedaa5dd2d96&quot;),
    phone: &quot;666&quot;
  }, {
    _id: new mongo.ObjectID(&quot;5f3258cfbaaccedaa5dd2da2&quot;),
    phone: &quot;555&quot;
  }]
  </code></pre>
  <p>from service B to service A?</p>
  <p>EDIT:</p>
  <p>The following works perfectly fine:</p>
  <pre><code>var q = { _id: new mongo.ObjectID(&quot;5f3258cfbaaccedaa5dd2d96&quot;) };
  const result = await this.db.collection(&quot;persons&quot;).find(q).toArray();
  </code></pre>
  <p>The following doesn't work:</p>
  <pre><code>var q = { _id: { $oid: &quot;5f3258cfbaaccedaa5dd2d96&quot; } }
  const result = await this.db.collection(&quot;persons&quot;).find(q).toArray();
  </code></pre>
  <p>Now,</p>
  <pre><code>var q = { _id: new mongo.ObjectID(&quot;5f3258cfbaaccedaa5dd2d96&quot;) };
  JSON.stringify(q)
  </code></pre>
  <p>gives you : <code>{&quot;_id&quot;:&quot;5f3258cfbaaccedaa5dd2d96&quot;}</code> and if you pass this to service A. You can not use it in service A as follows:</p>
  <pre><code>  const result = await this.db.collection(&quot;persons&quot;).find(qStr).toArray();
  </code></pre>
  <p>Or as,</p>
  <pre><code>  const result = await this.db.collection(&quot;persons&quot;).find(JSON.parse(qStr)).toArray();
  </code></pre>