在Firebase和Vue.js中批量写入添加文档和子集合。
实现方法如下:
1、引入Firebase依赖库。
import firebase from 'firebase/app'; import 'firebase/firestore';
2、初始化Firebase配置。
var firebaseConfig = { apiKey: "apiKey", authDomain: "authDomain", databaseURL: "databaseURL", projectId: "projectId", storageBucket: "storageBucket", messagingSenderId: "messagingSenderId", appId: "appId" };
const firebaseApp = firebase.initializeApp(firebaseConfig); const db = firebase.firestore();
3、创建一个要写入的新文档。
const newDocument = { title: 'New Document', content: 'This is a new document' };
4、创建一个新的子集合。
const newSubcollection = [ { title: 'Subcollection 1', content: 'This is subcollection 1' }, { title: 'Subcollection 2', content: 'This is subcollection 2' } ];
5、批量写入新文档和子集合。
let batch = db.batch();
//写入新文档 let newDocRef = db.collection('my_collection').doc(); batch.set(newDocRef, newDocument);
//写入新的子集合 let subcollectionRef = newDocRef.collection('my_subcollection'); newSubcollection.forEach((doc) => { let docRef = subcollectionRef.doc(); batch.set(docRef, doc); });
//提交批量写入操作 batch.commit().then(() => { console.log('Batch operation successful.'); }).catch((error) => { console.error('Error writing new batch operation.', error); });
以上代码将实现在Firebase和Vue.js中批量写入添加文档和子集合。