问题
I have some MongoDB documents with this schema:
Id: {type: "id", key: true, computed: true, nullable: false},
Name: {type: "string", nullable: false, maxLength: 50}
and these documents are exposed as OData by a small web application (I'm using Express, JayData, and Mongoose). These are some of those documents:
{ "_id" : ObjectId("5343fd656b9c5c084b8f2a70"), "Name" : "Service74"},
{ "_id" : ObjectId("5343fd656b9c5c084b8f2a6f"), "Name" : "Service73"},
{ "_id" : ObjectId("5343fd656b9c5c084b8f2a6e"), "Name" : "Service72"},
...
If I type this address http://localhost:8080/marketplace/Services('5343fd656b9c5c084b8f2a70')
which correspond to Service74 I get this result:
...
<d:Id>NTM0M2ZkNjU2YjljNWMwODRiOGYyYTcw</d:Id>
<d:Name>Service74</d:Name>
...
Of course If I use the Id specified in the result I obtain the same page.
The problem occurs when I try to use the mongoose function findById:
app.post("/addCompare/:id", function(req, res) {
console.log(req.params.id);
Services.findById(req.params.id, function(err, service) {
if(!err) {console.log(service);}
else {console.log(err);}
});
res.send(200);
});
I get this NTM0M2ZkNjU2YjljNWMwODRiOGYyYTcw
and then this error:
{ message: 'Cast to ObjectId failed for value "NTM0M2ZkNjU2YjljNWMwODRiOGYyYTU5" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'NTM0M2ZkNjU2YjljNWMwODRiOGYyYTU5',
path: '_id' }
Where am I wrong? Tell me if I miss some other information...
Thanks.
PS: I found a similar problem here Mongoose: Cast to ObjectId failed, but if I change the model definition for Mongoose (in which actually I don't declare the id) by including this definition:
var serviceSchema = mongoose.Schema({
_id: String,
...
nothing changes...
回答1:
The 5343fd656b9c5c084b8f2a70
is the internal identifier of the entity that is used on the server-side. This value is base64-encoded over OData, this is why you receive NTM0M2ZkNjU2YjljNWMwODRiOGYyYTcw
in the Id field. The entity can be easily retrieved by Id by calling atob(req.params.id)
on the received Id.
来源:https://stackoverflow.com/questions/23062042/odata-strange-index-with-mongodb-mongoose-cast-error