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.
Related
I have a mongodb schema like below.
const DemoSchema: Schema = new Schema({
demoProperty1: { type: String, required: true }
});
I create a document with syntax in node js server like below.
const savedDemo = await this.demoModel.create({demoProperty1:""});
Why it is returning error message
UnhandledPromiseRejectionWarning: ValidationError:
How to fix this issue?
From the documentation:
// Use this to allow empty strings to pass the `required` validator
mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
Yes I have fix this issue by trial and error.
Empty string is not eligible for mongodb required schema,
Took me 5 hours to figure it out. I can just passed in any string but not an empty string to make it valid and passed without any error.
As the title says.
For more context : I have a small script (launched by php via exec) that will search for a chapter with a given id to do some changes on the images (scramble them) that I didn't manage to do in php (I'm newbie working with files).
here are my schema
//instantiate mongoose-gridfs
var gridfs = require('mongoose-gridfs')({
collection:'files',
mongooseConnection: mongoose.connection
});
//Files = gridfs.model;
var FilesSchema = gridfs.schema;
FilesSchema.add({
_id: Schema.Types.ObjectId,
name: String,
mime: String,
filename: String,
type: String
});
Files = mongoose.model('Files', FilesSchema);
var pageSchema = Schema({
order: Number,
image: { type: Schema.Types.ObjectId, ref: 'Files' },
scrambled: Boolean
});
var ChapterSchema = Schema({
_id: Schema.Types.ObjectId,
pages: [pageSchema]
});
var Chapter = mongoose.model('Chapter', ChapterSchema, "Chapter");
When I do that
Chapter.findById(chapterId)
.populate('pages.image')
exec(...
It raises the CastError : { CastError: Cast to ObjectId failed for value "DBRef ...
The error object is long, so I don't paste it here
but here is a pastebin with the full error message/object
https://pastebin.com/8n54Dhzt
If I chan,ge the type of Image to Array I can access the properties I need after, but in that case I can't reset the images properly (it writes an array on db instead of a Ref)
My ref is in an embeddedDocument, like that
Chapter.pages[0].image
image is the property that have the ref.
I don't really understand why I have this error, I followed the docs for the refs/populate : http://mongoosejs.com/docs/populate.html
PS : A detail that can be important, The Reference is saved by DoctrineODM.
I use my node script to modify/encrypt the image, and then revert the encryption in js on my app.
PS2: sorry if a similar question is already posted and answered, there is so much post with the same error 'Cast to ObjectId failed for value' I admit I didn't read all of them, but those I read didn't help me.
EDIT : Update my code to use mongoose-gridfs Model instead of a different one + use subDocument instead of Array of object
Well that seems an error with chapterIdvalue. When you use collection.findById, the passed value must pass the ObjectId criteria which is
12-byte structure, the first 4 bytes of the ObjectId represent the
time in seconds since the UNIX epoch.
The next 3 bytes of the ObjectId represent the machine identifier.
The next 2 bytes of the ObjectId represent the process ID.
And the last 3 bytes of the ObjectId represent a random counter
value.
And if your passed id is not constructable to the pattern mentioned above this is definitely gonna throw the errors like you're getting.
So make sure you chapterId is correct or it is the same what you are getting from the database
I am trying to convert a string to ObjectId using
var body={};
var objId="57b40595866fdab90268321e";
body.id=mongoose.Types.ObjectId(objId);
myModel.collection.insert(body,function(err,data){
//causing err;
});
the above code is working fine when mongoose 4.4.16 is used, but if i update my mongoose to latest version(4.6.0) then problem occurs.
Err
object [
{
"_bsontype":"ObjectID",
"id:{"0":87,"1":180,"2":5,"3":235,"4":134,"5":111,"6":218,"7":185,"8":2,"9":104,"10":50,"11":111}
}
]
is not a valid ObjectId
The right way to insert new document is-
var newDocument = new myModel({
_id: mongoose.Types.ObjectId("57b40595866fdab90268321e")
});
newDocument.save();
In you case-
It stops working because the differences between versions of mongoose and mongo native drivers.
although, you are able to perform this by the example above, or, if you still want to use insert, you can use the myModel.insertMany (by passing object instead of array)
look here
http://mongoosejs.com/docs/api.html#model_Model.insertMany
I don't have the time to spike it, but if I remember correctly id is a simple string and _id is the ObjectId, i.e. either
body.id="57b40595866fdab90268321e"
or
body._id=mongoose.Types.ObjectId("57b40595866fdab90268321e");
That said, does it have to be that specific id? If not, you can use new myModel() and an id will be automatically created.
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"
I'm learning to use with mongoose and node.js when editing to generate a content that gives me the error: 500 TypeError: Can not read property 'ObjectID' of undefined. Check whether the parameter that I send comes empty and is not.
Remove the option and gives me that error when saving the data did not find the method I use to save some registry update.
If I can help as I have code in https://github.com/boneyking/PruebaNode.git
First of all, please provide code or at least a link to the code. A link to your github repo is not cool !!!
Now back to the question... Add an id to your model and get it like other types:
var SUPER = mongoose.model('Producto',{
nombre: String,
descripcion: String,
precio: Number,
id: mongoose.Schema.Types.ObjectId
});
SUPER.editar = function(newData, callback){
SUPER.findOne({id: newData.id}, function(e,o){
o.nombre = newData.nombre;
o.descripcion = newData.descripcion;
o.precio = newData.precio;
SUPER.save(o);
callback(o);
});
}