Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

firestore database showing user map instead of reference

Here is what I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

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(),
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading