タイトルと著者による本の引用を保存して表示するアプリを作成しようとしています。バックエンドにFirebaseを使用しています。私のFirebaseデータ構造は次のようになります。
本の引用が追加されるとき、私は著者を知っています。そのため、見積もりを作成者に自動的に保存するために、FirebaseFunctionsを使用しようとしています。
私は2つのアプローチを試しました。
本が更新されたときに、著者からの引用と本からの引用をマージします。
exports.newQuotesTrigger = functions.database.ref('library/{bookAndAuthor}').onWrite((snap, context) => {
const message = snap;
console.log('Retrieved message content: ', message);
const newValue = message.after.val();
const oldValue = message.before.val();
const author = snakeCase(newValue.author);
admin.database().ref('authors/' + author).child('quotes').set(newValue.quotes);
console.log('Updated author quotes');
return message;
});
本から新しい引用と古い引用の違いをプッシュするだけです
exports.newQuotesTrigger = functions.database.ref('library/{bookAndAuthor}').onWrite((snap, context) => {
const message = snap;
console.log('Retrieved message content: ', message);
const newValue = message.after.val();
const oldValue = message.before.val();
const newQuotes = newValue.quotes || [];
const oldQuotes = oldValue.quotes || [];
const diff = arrayDiff(newQuotes, oldQuotes);
if (diff) {
console.log('Quotes were updated for ', {title: newValue.title, author: newValue.author});
const author = snakeCase(newValue.author);
admin.database().ref('authors/' + author).child('quotes').push(diff);
console.log('Updated author quotes');
}
return message;
});
どちらも更新引用符を適切に追加/挿入しません。Firebaseデータベース配列に追加/挿入する方法が見つかりませんでした。
You have to use update in order to "update specific children of a node without overwriting other child nodes", see:
https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields
Your first piece of code should work with update if you slightly change your structure as follow with autogenerated Ids for the quotes
Database
author
- nassim
- quoteID1: "...." <- ID auto generated
- quoteID2: "...." <- ID auto generated
- quoteID3: "...." <- ID auto generated
Cloud Function
Replace, in your first version of the code, these lines
admin.database().ref('authors/' + author).child('quotes').set(newValue.quotes);
console.log('Updated author quotes');
return message;
by those ones
const quotesObject = newValue.quotes;
var updates = {};
Object.keys(quotesObject).forEach(function (key) {
let quote = quotesObject[key];
const newQuoteKey = firebase.database().ref('authors/' + author).child('quotes').push().key;
updates[newQuoteKey] = quote ;
});
return admin.database().ref('authors/' + author).child('quotes').update(updates);
Another important point is that you are not returning a promise in your Cloud Functions. You should return the promise from the update (or set) and not the message. See https://www.youtube.com/watch?v=652XeeKNHSk&t=26s
自分で生成した引用符ID(0、1、2など)を順番に保持する必要がある場合は、前の値の配列を取得し、新しい引用符を追加して、の既存のセットを上書きすることにより、配列を操作する必要があります。新しい配列で引用します..多くの努力!特に、自動生成されたIDを使用すると、引用符の順序が失われることはありません。引用符は、書き込まれた順序で保存されます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加