Svelte应用程序可以读取firebase数据库,但不能添加



你好,stackoverflow社区。我正在使用Svelte、MaterializeCSS和firebase制作一个简单的数据库应用程序。我能够从firebase数据库中读取,所以我知道这不是凭据问题,但是在使用下面的"addLink"函数时,数据库不会更新。警报会正确显示日期和newLink字符串。上下文中的代码也在下面。

function addLink() {
alert(date.getTime());
db.collection("links").add({ link: newLink, id: date.getTime() });
}
<script>
import GetForm from "../layout/GetForm.svelte";
import TranslateButton from "../layout/TranslateButton.svelte";
import { db } from "../firebase.js";
let arrList = [];
let newLink = "";
let date = new Date();
db.collection("links")
.orderBy("id", "asc")
.onSnapshot(snapData => {
arrList = snapData.docs;
});
function addLink() {
alert(date.getTime());
db.collection("links").add({ link: newLink, id: date.getTime() });
}
</script>
<div class="container right-align" style="margin-top: 30px;">
<TranslateButton />
</div>
<div class="container" style="margin-top: 150px;">
<div class="row">
<div class="center-align">
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s10">
<textarea
id="textarea1"
class="materialize-textarea"
bind:value={newLink} />
<label for="textarea1">Put your URL here.</label>
</div>
<button
class="btn waves-effect waves-light col s2"
on:click={addLink}>
Send
<i class="material-icons right">arrow_forward</i>
</button>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class="center-align">
<GetForm />
</div>
</div>
<ul>
{#each arrList as listItem}
<li>{listItem.data().link}</li>
{/each}
</ul>
</div>

根据官方文档Set a Document的说明,您需要使用方法set()将文档添加到您的集合中。在数据库中插入的一个例子如下-文档在Node.js中,但我认为它应该作为一个起点对您有所帮助。

let data = {
link: 'Link you want',
id: 'Id you want'
};
let setDoc = db.collection('link').doc('Id').set(data);

这只是将文档添加到集合的一个简单示例,但它应该有助于您理解您的逻辑。

除此之外,在下面的文章中,您应该了解有关如何在Firestore上执行查询的更多信息。

  • 开始使用Cloud Firestore
  • 添加数据

如果这些信息对您有帮助,请告诉我!

在Firestore DB中添加新条目

你在学习哪个firebase教程?这不是向firebase添加数据的方式。用set()替换add()

对于自动生成的ID

将"无"作为参数传递给doc()

// For automatically generated id
db.collection('links')
.doc()
.set({ link: newLink })  
.then(() => {  // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data())  // prints {link: newLink, id: 1321415}
})
})

用于使用您自己的id

将您的id作为参数传递给doc()

// Or you could set your own id, which is in your case,
// Pass your `id` as argument for `doc()`
db.collection("links")
.doc(date.getTime())
.set({
link: newLink
})

将数据添加到Cloud Firestore

相关内容

最新更新