Unable to assign a random string to _id field. - node.js

I am trying to save a document into mongodb using MONK drive.
My object has a field called myid, which is a string of unknown length. I'm very inclined to use this ID as _id of my document but after I assign the value to _id field and save the document, I receive error as below:
Error: Argument passed in must be a single String of 12 bytes or a string of 24
hex characters
Is this some restriction introduced by MONK or MongoDB driver? Is there anyway to workaround this? In mongodb shell, you can use any value as _id;

It is an error thrown by monk. You can override the id function:
collectionName.id = function(str){return str;};
See: GitHub issue

Related

db.collectionsname.findOne({mobilenumber: mobilenumber}).feildname

Im not able to fetch the field value i need only the value of the particular field in node js query, but coming undefined
I need the nodejs query of this mongodb query
Try using projection into find query to return only values you want.
Also don't forget to use await or get the field name into then. And, of course, the query should return any document to get the field.
Check this example which would be similar in Node:
const value = await db.collectionsname.findOne({mobilenumber: mobilenumber},{_id: 0, field: 1}).fieldname
Projection stage is not mandatory but if you only want that value is a good practice not get all document from the DB.

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

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}})
Assuming you're using the Nodejs Mongodb driver and not some ORM (since it hasn't been specified), two points of concern:
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.
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.

Is it possible to update MongoDB String field with a String that is an ObjectId in Python

So I have a String array field in MongoDB collection that I would like to add a String that is an ObjectId. It gets added but gets saved as an ObjectId instead of a String.
users_collection.update_one({
"_id": ObjectId(user['_id'])
}, {
"$push": {
"profile.surveys.completedInTimeSurveyIDs": "5dc71ee34283e125a9edc96b"
}
})
Which always saves in the collection document as:
But I want it to be:
Likely you have defined a schema in your framework and your framework know that the type of the value referred by your path (here profile.surveys.completedInTimeSurveyIDs.$ would have been specified as oid and thus your string is cast as so)
Alternatives are:
design your schema according to your spec (as a string)
bypass the framework and directly use the driver (if exceptional and possible)
consider really storing an ObjectId and adapt your code upon retrieval (str() if needed)
I would advise you to do the latter (if you were to aggregate stuff, lookup, even populate, or any other work involving your array element, you are likely to need an ObjectId)

Cast to ObjectId error when doing findOneAndUpdate

I have a collection jobs that references a collection users via a jobOwner field and i'm using Mongoose as my ORM.
When i try Job.findOneAndUpdate({jobOwner:userId})
I get the error "Cast to ObjectId failed for value "user" at path "jobOwner""
userId is a string with the appropriate _id of the user. I've tried converting it to an objectId by doing userId = mongoose.Types.ObjectId(userId) and I still get the same error.
What can i do to fix this?
It seems that your id value equals "user" instead of a valid object id that it is expecting. Log it to console and check. You probably have a mistake somewhere.

MongoDB / Node.JS: Get attribute value from document

I have a document:
{
"_id":ObjectId("someID")
"email":"john#example.com"
}
I would like to retrieve "john#example.com" so that I can pass this value to the browser.
How do I do that?
I saw these SO posts, but I don't understand the solution at all:
How to get string value inside a Mongodb document?
How to get value from a MongoDB document

Resources