📅  最后修改于: 2023-12-03 14:41:12.320000             🧑  作者: Mango
Firebase Firestore is a cloud-hosted database from Google that is designed to store and sync data for client-side development. It's a NoSQL document database that can be used to store and retrieve data in real-time.
To get started with Firebase Firestore, you first need to create a Firebase project and enable Firestore in your project. Then, you can start using Firestore in your application by adding the necessary code to initialize, read, write, and query data from the database.
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Get a reference to the Firestore database service
const db = firebase.firestore();
// Add data to the database
db.collection("users").add({
name: "John Doe",
email: "johndoe@example.com",
age: 30
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
// Read data from the database
db.collection("users").get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
})
.catch((error) => {
console.error("Error getting documents: ", error);
});
// Query data from the database
db.collection("users").where("age", ">=", 25).get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
})
.catch((error) => {
console.error("Error getting documents: ", error);
});
Firebase Firestore allows you to write security rules to protect your data from unauthorized access or modification. You can define rules at the project, database, or collection level to restrict access based on user authentication, data validation, or custom conditions.
Here's an example of a security rule that requires users to be authenticated before they can read or write data:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
Firebase Firestore is a powerful and flexible database solution that is well-suited for client-side development. It provides real-time data synchronization, offline support, and powerful querying capabilities, making it easy to build robust and responsive applications. With Firebase services like Authentication, Cloud Storage, and Cloud Functions, you can extend the capabilities of Firestore even further and build scalable and secure applications in the cloud.