【发布时间】:2020-08-23 09:46:21
【问题描述】:
我正在编写一些 Node.js 代码,以将现有数据库中的数据导入 Firebase Cloud Firestore。我们已经创建了我希望在过渡中保留的日期和更新日期。问题是我们创建了 Cloud Functions 来自动设置对象创建时的设置,因此它总是用当前时间戳覆盖对象的值。如果我再次运行我们的导入脚本,因此 set 正在更新现有文档,则保留对象中的 createdAt 和 updatedAt 值。
我怎样才能让它使用指定的值而不用创建时的当前时间戳覆盖它们?
const oldNote = {
id: "someid",
text: "sometext",
createdAt: new Date(2018, 11, 24, 10, 33, 30, 0),
updatedAt: new Date(2018, 11, 24, 10, 33, 30, 0)
}
const note = {
text: oldNote.text,
createdAt: firebase.firestore.Timestamp.fromDate(oldNote.createdAt),
updatedAt: firebase.firestore.Timestamp.fromDate(oldNote.updatedAt)
};
firestoredb.collection("notes").doc(oldNote.id).set(note).then((docRef) => {
//FIXME: createdAt and updatedAt aren't preserved, always today
}).catch((error) => {
console.error("Error setting user: ", error);
});
这里是云函数:
exports.updateCreatedAt = functions.firestore
.document("{collectionName}/{id}")
.onCreate((snap, context) => {
const now = admin.firestore.FieldValue.serverTimestamp();
return snap.ref.set(
{
createdAt: now,
updatedAt: now
},
{ merge: true }
);
});
exports.updateUpdatedAt = functions.firestore
.document("{collectionName}/{id}")
.onUpdate((change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
if (
Boolean(newValue.updatedAt) &&
Boolean(previousValue.updatedAt) &&
newValue.updatedAt.isEqual(previousValue.updatedAt)
) {
const now = admin.firestore.FieldValue.serverTimestamp();
return change.after.ref.set({ updatedAt: now }, { merge: true });
} else {
return false;
}
});
【问题讨论】:
-
dateobj到底是什么?请不遗余力。我们应该能够获取您的代码并自己运行它。 -
@DougStevenson 这是一个 JavaScript 日期对象。这只是一个例子,旧笔记是从不同的数据库中查询的。
-
确切的值很重要。
标签: javascript firebase google-cloud-firestore google-cloud-functions