繁体   English   中英

如何将 Firestore 文档引用存储为 nextjs 中的字段?

[英]How do I store a Firestore document reference as a field from nextjs?

我正在创建简单的博客帖子并尝试将帖子连接到登录用户。 当我创建一个文档引用以存储为具有引用类型的字段时,我得到一个 map,如下所示:

firestore 数据库显示用户地图而不是参考

这是我试过的

登录用户存储在上下文中,数据与用户一起发送到 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: ''}) 
  }
}

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;

不要直接从前端传递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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM