How to parse MongoDB document string in NodeJS - node.js

Is there a way to parse a user-entered MongoDB document (a string) into a mongodb/Mongoose document which can be inserted to database?
Example string
'{ "name": "Dave", "location_id" : ObjectId("5d8664a9b1b0ae25d60e0e42") }'

Yes, this can be done by utilising JSON.parse(), unfortunately, if that data you're passing does have an ObjectId() as the example string in your question does this will fail as it's invalid JSON.
Assuming your example string is wrong and you're not trying to pass in an object id you can do it this way:
...
const client = await mongodb.connect("connection-string");
const doc = JSON.parse('{ "name": "Dave", "location_id" : "5d8664a9b1b0ae25d60e0e42" }');
await client.db("my-db").collection("my-data").insertOne(doc);
...
If you are passing in invalid JSON such as the ObjectId then you will need to perform steps to remove it and pass in it's value as a string, and then add the location_id property manually before inserting:
...
doc.location_id = new mongodb.ObjectID(doc.location_id);
...

Related

I need to be able to obtain only the string that makes up the Id in a query to MongoDB

I'm using mongoDB, mongoose and typescript and I need to keep the document ids when I query but I can only get the type _id: new ObjectId("62aa4bddae588fb13e8df552") . I only need to keep the string "62aa4bddae588fb13e8df552" to later store it and do other processing. I can't get rid of the new ObjectId
async findById(id:string) {
const convert = {"_id":id}
const userfindById = await userModel.findById(convert);
const iD = userfindById?._id
return userfindById;
}
ObjectId is just a type :
https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-objectid
If you want to get the string you can extract with _id.toString(), if you want to store the string you should change the type of _id (or create a new property)

failed: id is not defined while parsing unsing mongoose

So I am trying to parse some data using mongoose my schema looks like
data: [{
'order-id': String,
'sku': String,
'purchase-date': String,
'payments-date': String,
and I am trying to get the data using :
let parseddata = new ParsedDataModel(doc) ;
parseddata.data[0].order-id // failed id is not defined
While
parseddata.data[0].sku // is working
Is this a problem with the dash 6 ? How can I solve it ?
The problem is with your "dash".
Node js thinks it is a "minus" and your id is another variable.
Try using the following:
parseddata.data[0]["order-id"]
PS: I would recommend using ObjectId as the type for order-id instead of String. You can then populate the order document directly from this itself.

single quote added to string when building a mongo string

I am trying to build query string to find documents in mongodb.
I have a variable assigned for the value in the key:value pair.
My code looks like below
var query = {"_id":orgId[0]};
var name = "_id";
console.log(query);
db.collection('orgs')
.findOne({query}, function (err,result) {
});
The value of query looks like the below
{ _id: '"567a701be4b017"' }
Its basically adding a single quote around the string value and therefor the result from the query is null. How can i get past this ?
Thanks
Sam

Argument passed in must be a single String of 12 bytes

mongoDB collection contains the following data
db.stack.find()
{ "_id" : "8GieRu" }
The _id is not single String of 12 bytes,
As per the MongoDB document of [ObjectID][1], id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.
Using Mongoose this collection is accessed using this Json
{"_id" : new mongoose.Types.ObjectId("8GieRu")}
and throws the below error
/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:35
throw new Error("Argument passed in must be a single String of 12 bytes or
^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:35:11)
[1]: http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html
Mongoose is strictly checking the ObjectId of fixed length, how can i pass Object_id using mongoose with the given length
You mix two concepts here.
While "_id" can have any value (even subdocument like {firstName:'Foo',lastName:'Simpson'}, "ObjectId" has a fixed set of types with some restrictions, as the error message correctly states.
So your statement should be
{'_id':'putWhatEverYouWantHere'}
I had the problem in my router order:
app.get('/jobs', controllers.jobs.getAllJobs);
app.get('/jobs/karriere', controllers.jobs.getAllJobsXML);
app.get('/jobs/:id', controllers.jobs.getJob);
app.get('/jobs/:id/xml', controllers.jobs.getJobXML);
I defined /jobs/karriere after /jobs/:id so the application thought that "karriere" was an ObjectID and returned the error. The code above is the working one.
Make sure the method you are using in client and server side match. This error also shows when you have e.g. GET being sent from client side and POST required on the server side.
You are passing any
ObjectID undefinded
If the ObjectID is undfined thaen this error will come.
In my case, I'm using mongoose. and I am not able to query with something like this:
{ "_id" : "8GieRu" }
Until I bumped into my model file and specified this line counter.model.js
var CounterSchema = new Schema({
_id: String,
sequence_value: Number
})
Notice that I specified the data type as string for _id in my model.
and the, in my query, I didn't need to convert string to ObjectId.
Query now works as simple as what the filter:
{ "_id" : "8GieRu" }
same problem faced by me but after a RND . I identified that i passed wrong {Id:Undefined} so problem occured so please firstly check your Id which you passed in URL.
Error = "http://localhost:4000/api/deleteBook/Undefined"
Right = "http://localhost:4000/api/deleteBook/5bb9e79df82c0151fc0cd5c8"

find function in mongodb and literal objects

I use Mongoose on nodeJS and I have the following schema in MongoDB:
var users = new Schema({
local: {
user_uuid: String
,user_name: String
,password: String
,email: String
,connectionKey: String
}
});
And I'm exporting the schema in the following way:
module.exports.users = mongoose.model('users',users);
and this is my find statment:
var AllSchemas = require('../schemas/schemas');
...
AllSchemas.users.find({ user_uuid: doctorId},function(err,obj){
...
}
but I get that the user is not found.
If I take all the parameters out of the literal object "local" it will work
I want to know how can I find things inside a literal object.
You need to use dot notation to reach inside of embedded documents in your query:
AllSchemas.users.find({ 'local.user_uuid': doctorId }, function(err,obj) {
...
}
While referring to a sub object in the schema, you should use the dot notation inside quotes.
Please refer the following link to get the more information about the dot notation
http://docs.mongodb.org/manual/core/document/#document-dot-notation
In your case, you should use:
AllSchemas.users.find({ 'local.user_uuid': doctorId},function(err,obj){
...
}
This query will return you all the documents having user_uuid equal to doctorId.

Resources