Description
Description
versions :
js-data: 3.0.0-rc.6
js-data-mongodb : 1.0.0-rc.1
Steps to reproduce
Here is my model schema :
{
"type": "object",
"properties": {
"a": {
"type": "string"
},
"b": {
"type": "string"
}
},
"required": ["a"],
"additionalProperties": false
}
When i insert or update not all the properties of my model (example with only property "a" : {a: "a"}
), the others properties are set to undefined
by js-data. So the input props
of methods create
or update
looks like :
{
a: "a",
b: undefined
}
The problem is that the Node.js mongodb driver, insert null
in the database for all the undefined
properties. So when you just want to update property "a", the previous value of property "b" is erase by a null
value.
The workaround solution i found, is to remove all undefined properties of the object in methods beforeCreate
and beforeUpdate
on the adapter. But i think it could be made directly on insert or update methods.
// Workaround to avoid undefined values to be set to null in MongoDB
const adapter = new MongoDBAdapter({
uri: config.MONGODB_URI,
beforeUpdate(mapper, id, props) {
const removeUndefined = (obj) => {
Object.keys(obj).forEach(key =>
(obj[key] && typeof obj[key] === 'object') && removeUndefined(obj[key]) ||
(obj[key] === undefined) && delete obj[key]
);
return obj;
};
removeUndefined(props);
}
});
Solution can be found here : http://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript. It should be recursive and only remove undefined properties.
Any thoughts ?
Thanks!