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:
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:
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
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;
CodePudding user response:
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:
// 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(),
});