We have a variety of nested configurations stored in MongoDB.
- Initially, we store the following object in MongoDB:
const value = { 'a': { 'b': 1 } }
collection.insertOne({userId, value})
Now, I would like to modify the object in the database by adding
const addValue = { 'f': { 'c': 2 } }
as well as a few more nested objects.
const addValue1 = { 'a': { 'd': 1 }, 'f': { 'g': 1 } };
As these keys are dynamic and the values should be updated without replacing them, the expected end result stored should be
const result = collection.findOne({ userId });
console.log(result);
{ 'a': { 'b': 1, 'd': 1 }, 'f': { 'g': 1, 'c': 2 } }
Also, if the update value is to overwrite existing data,
const addValue2 = { 'a': { 'b' : { 'e': 1 } } }
the expected result is
const result2 = { 'a': { 'b': { 'e': 1 } , 'd': 1 }, 'f': { 'g': 1, 'c': 2 } }
Similarly, when deleting items
let testObject = new MongoDBStorageService('test', dbConnection as any, 'userTestSchema');
testObject.load({ 'a': { 'b': 1 }});
testObject.removeValue('a.b');
const content = await testObject.contents;
expect(content).toEqual({}); // but we see output as `{ a: {} }`
A Remove method example
public async removeValue(key: string) {
return await this.remove(JSON.parse(`{\"${key}\": "" }`));
}
private remove(value) {
return new Promise((resolve, reject) => {
this.collection.updateOne({ user: this.userId }, {
$unset: value,
}, { upsert: false }, function (err, res) {
if (err) {
reject(err);
} else {
console.log('RESULT AFTER REMOVE', res.);
resolve({ id: true });
}
});
});
}