Mongodb finding a record by native id generated Node.js backend

90 views Asked by At

First time working with MongoDB. This query works for me in cmd line:

db.secrets.update({_id: ObjectId("5f767cd481cea1687b3dbf86")}, {$set: {secret_rating: 5}})

However, updating a record using essentially the same query on my node server is not completing this task when pinged. Am I wrong in trying to query for a record like so in my model? ObjectId obviously isn't native to my server.

db.secrets.update({_id: "5f767cd481cea1687b3dbf86"}, {$set: {secret_rating: 5}})
1

There are 1 answers

0
Anuj Pancholi On

Assuming you're using the Nodejs Mongodb driver and not some ORM (since it hasn't been specified), two points of concern:

  1. As far as my knowledge serves, if you have a connection object to your desired database in the db variable, you cannot reference collections directly such as you've done with db.secrets; you must instead use the collection method like so:

const secrets = db.collection("secrets");

secrets.find({
    /*your query here*/
}).then((results) => {})

So, unless you've assigned db.secrets with db.collection("secrets") you should be getting an error, Cannot read property "update" of undefined. But I'm going to assume you've got the collection object in db.secrets since you did not mention you're getting that error.

  1. You seem to be using a string instead of an ObjectID object. You can import the ObjectID constructor from the nodejs driver like so:

const ObjectID = require('mongodb').ObjectID

Then in your query, you will have to make a new ObjectID to get the correct result:

db.collection("secrets").find({
    _id: new ObjectID("5f767cd481cea1687b3dbf86")
}).then((results) => {})

NOTE: The ObjectID constructor will throw an error if the string supplied to it is not a valid, 24-char hex string, so, if you're getting the id string as an input from somewhere (say, as a parameter in an API or as a command line argument), you might want to wrap it in a function that handles that error.