Cloud Firestore: 동적 키를 사용하여 중첩된 개체의 필드 업데이트
소방서 공식 문서에 따름:
{
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess" },
age: 12
}
// To update favorite color:
db.collection("users").doc("frank").update({
"favorites.color": "Red"
})
저는 색상 대신 동적 키를 사용하고 싶습니다.
db.collection("users").doc("frank").update({
"favorites[" + KEY + "].color": true
});
물론 이것은 가능하지 않으며 오류를 발생시킬 것입니다.
저는 이것을 하려고 노력해왔습니다.
db.collection("users").doc("frank").update({
favorites: {
[key]: {
color": true
}
}
});
실제로 올바른 키로 업데이트하고 있지만 안타깝게도 다른 키를 덮어쓰고 있습니다(삭제 중).
저는 파이어베이스 솔루션("/"을 "."로 대체)에서 영감을 얻은 솔루션을 발견했습니다.
var usersUpdate = {};
usersUpdate[`favorites.${key}.color`] = true;
db.collection("users").doc("frank").update(usersUpdate);
이 솔루션은 저에게 효과가 있었습니다.
db.collection('users').doc('frank').update({
[`favorites.${key}.color`]: true
});
잠재적인 함정에 대한 참고 사항: 점 구문을 사용하여 중첩된 필드를 업데이트할 수 있다는 것을 발견한 후 다음을 사용해 보았습니다.set()
동일한 방식으로, 객체가 이미 존재하는지 여부에 관계없이 작동하기 위해 필요했기 때문에:
var updateObj = {['some.nested.property']: 9000};
docRef.set(updateOb, {merge: true});
불행히도 이것은 작동하지 않습니다. 이것은 키가 다음과 같은 속성을 설정합니다.some.nested.property
대신.일관성은 없지만 좋습니다.
다행히도, 그들은set(updateObj, {merge: true})
에서는 딥 병합을 수행하므로 업데이트 개체를 완전히 중첩된 개체로 구성하면 중첩된 개체도 올바르게 병합됩니다.
// create the object
db.doc('testCollection/doc').set({p1: {['p2']: {p3: true}}}, {merge: true})
// update the existing object
db.doc('testCollection/doc').set({p1: {['p2']: {p4: true}}}, {merge: true})
// result is now this:
{ p1: { p2: { p4: true, p3: true } } }
이름이 지정된 중첩 개체의 특정 필드를 아래와 같이 업데이트할 수 있습니다.
ref.set({
name: "Frank",
favorites: { food: "Pizza", quantity: 2 }
});
//now the relevant update code
var name = "favorites";
var qty = 111;
var update = {};
update[name+".quantity"] = qty;
ref.update(update);
https://jsbin.com/hihifedizu/edit?js,console
저는 이것이 위의 모든 것들 중 가장 간단한 해결책이라고 느꼈습니다 :)
db.collection("users").doc("frank").update({
[`favorites.${KEY}.color`]: true
});
사용할 수 있습니다.
var auxKey = "history." + someVar;
var dataToUpdate = {
[auxKey]: "new data generated"
};
db.collection("users").doc("frank").update(dataToUpdate);
2022 웹 버전 9(모듈형)로 업데이트:
const docRef = doc(db, 'users', frank);
var usersUpdate = {};
usersUpdate[`favorites.${key}.color`] = true;
updateDoc(docRef, userUpdate);
언급URL : https://stackoverflow.com/questions/47295541/cloud-firestore-update-fields-in-nested-objects-with-dynamic-key
'sourcecode' 카테고리의 다른 글
JDBC 연결 기본 자동 커밋 동작 (0) | 2023.06.13 |
---|---|
asp.net MVC에서 LabelForHelper를 사용하지 않고 DisplayName 특성을 가져옵니다. (0) | 2023.06.13 |
dbms_lob.create temporary()의 요점은 무엇입니까? (0) | 2023.06.13 |
RxJS 관찰 가능한 필터에서 정의되지 않음 (0) | 2023.06.13 |
스토리보드 - AppDelegate의 ViewController 참조 (0) | 2023.06.13 |