[英]How do I store a Firestore document reference as a field from nextjs?
Im creating simple blog posts and trying to connect the post to the logged in user.我正在创建简单的博客帖子并尝试将帖子连接到登录用户。 When i create a document reference to be stored as a field with reference type, I get a map as shown below:当我创建一个文档引用以存储为具有引用类型的字段时,我得到一个 map,如下所示:
Here is what I tried这是我试过的
The logged in user is stored in context and the data is sent to an api route along with user as a reference that already exists in the database:登录用户存储在上下文中,数据与用户一起发送到 api 路由,作为数据库中已存在的参考:
import {useAuth} from '../../context/AuthContext';
page function() {
const {user} = useAuth();
const onSubmit = async () => {
const { title, body } = content;
await axios.post('/api/post', {title, slug: dashify(title), body, author: doc(db, 'users/' + user.uid)
setContent({title: '', content: ''})
}
}
the api code is as follows api代码如下
const handler = async (req, res) => {
try {
const posts = await getDocs(postsRef);
const postsData = posts.docs.map((post) => post.data());
if (postsData.some((post) => post.slug == "slug")) res.status(406).end();
else {
const newPost = await addDoc(collection(db, 'posts'), {
...req.body,
createdAt: serverTimestamp(),
});
log(newPost, "post details");
res.status(200).json({ newPost });
}
// res.status(201).json({ author });
} catch (e) {
log(e, "error occured post");
res.status(400).end();
}
};
export default handler;
Instead of passing a DocumentReference
directly from frontend, try passing the document path and then create a DocumentReference
object on server side as shown below:不要直接从前端传递DocumentReference
,而是尝试传递文档路径,然后在服务器端创建一个DocumentReference
object,如下所示:
// API request
await axios.post('/api/post', {
title,
slug: dashify(title),
body,
author: `users/${user.uid}`
})
// Handler
const newPost = await addDoc(collection(db, 'posts'), {
...req.body,
author: doc(db, req.body.author)
createdAt: serverTimestamp(),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.