. Advertisement .
..3..
. Advertisement .
..4..
Here is the program I run:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId; //Have also tried Schema.Types.ObjectId, mongoose.ObjectId
mongoose.connect('mongodb://user:password@server:port/database');
app.get('/myClass/:Id/childClass/create', function(request, result) {
var id = new ObjectId(request.params.Id);
MyClass.findById(id).exec( function(err, myClass) {
if (err || !myClass) { result.send("error: " + err + "<br>" + JSON.stringify(id) || ("object '" + request.params.Id + "' not found: " + id)); return; }
var child = ChildClass();
myClass.Children.addToSet(child);
myClass.save();
result.send(child);
});
});
After I run, it returns an error:
TypeError: Object {} has no method 'cast'
CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"
error: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"
{"path":"51c35e5ced18cb901d000001","instance":"ObjectID","validators":[],"setters":[],"getters":[],"_index":null}
Does anyone have any suggestions for the problem below: casterror: cast to objectid failed for value in the javascript- How to correct it?
The cause: I think the cause of this error is that the value in the _id field that you want to filter is not in an ID format.
Solution: Always verify that the search criterion value is a valid ObjectId to fix this error
Short answer: use mongoose.Types.ObjectId.
Mongoose, but not mongo, can accept object IDs as strings and “cast” them for you.
The caveat is that
req.params.id
may not be a valid format to use with a mongo ID string. This will throw an exception, which you need to catch.The main thing to remember is that
mongoose.SchemaTypes
contains stuff you use for defining mongoose schemes, whilemongoose.Types
contains stuff you use to create data objects you want stored in the database.mongoose.Types.ObjectId("51bb793aca2ab77a3200000d")
will create an object that you can store in the database, or use in queries. If you give an invalid ID string, it will throw an exception.findOne
takes a query object, and passes one model instance to the callback.findById
is a wrapper forfindOne({_id: id})
( ).find
simply takes a query object, and passes an array with matching model instances to its callback.Take it slow. Although it’s confusing, I guarantee that you won’t get lost and you will not be able to hit bugs in mongoose. Although it’s a mature library, it can be difficult to master.
Another thing that I suspect is your
new
not being used when instantiatingChildClass
. To help us find any CastErrors, we will need your schema code.