scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
556 stars 80 forks source link

Documentation comment #39

Open scowling opened 8 years ago

scowling commented 8 years ago

Just a comment for the documentation re. loadOneAndUpdate For the people who have the same problem I had - you can't pass _id through in the values It will fail silently (almost). Took some digging to find out why.

I've scrubbed the property from the object in my code, but could loadOneAndUpdate do that by default?

scottwrobinson commented 8 years ago

Just to make sure I know exactly what you're talking about, can you post an example of the code that didn't work?

Are you trying to use _id as a field in your model? If so, that is a reserved field name and shouldn't be used, which I should probably make more explicit.

Thanks for posting the issue!

scowling commented 8 years ago

Yeah sure - and making the _id reservation more explicit is probably all that you need to do. This is is the code I was trying to use:

var component = args.params instanceof Component ? args.params : Component.create(args.params);
var params = component.toJSON();
Component.loadOneAndUpdate({_id:component._id},params,{returnOriginal:true, upsert: true})
.then(function(c){
    callback(null, {component:component})
})

But of course, params can sometimes contain a populated _id property - which would fail with an unhelpful 500 error from Mongo. I changed to the following code, all good now:

var component = args.params instanceof Component ? args.params : Component.create(args.params);
var params = component.toJSON();
if(component._id !== null){
    delete params["_id"];
}
Component.loadOneAndUpdate({_id:component._id},params,{returnOriginal:true, upsert: true})
.then(function(c){
    callback(null, {component:component})
})