【发布时间】:2020-01-28 23:21:19
【问题描述】:
我们有一些任意嵌套的配置存储在 mongodb 中。
- 假设我们最初将以下对象存储在 mongodb 中。
const value = { 'a': { 'b': 1 } }
collection.insertOne({userId, value})
现在我想通过添加来修改数据库中的对象
const addValue = { 'f': { 'c': 2 } }
类似地,还有更多的嵌套对象。
const addValue1 = { 'a': { 'd': 1 }, 'f': { 'g': 1 } };
正如我们添加的那样,这些keys 非常动态,应该能够更新数据库中的值但不能替换它,因此期望存储的最终结果应该是
const result = collection.findOne({ userId });
console.log(result);
{ 'a': { 'b': 1, 'd': 1 }, 'f': { 'g': 1, 'c': 2 } }
如果 udpate 值是也覆盖
const addValue2 = { 'a': { 'b' : { 'e': 1 } } }
预期结果是
const result2 = { 'a': { 'b': { 'e': 1 } , 'd': 1 }, 'f': { 'g': 1, 'c': 2 } }
删除时也一样
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: {} }`
删除使用的方法
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('REUSLL AFTER REMOVE', res.);
resolve({ id: true });
}
});
});
}
【问题讨论】:
标签: javascript mongodb mongodb-query