I'm taking form data and performing a lookup on the URL. Then trying to update the database with the form data and the lookup data at the same time.
I'm getting a 500 Error from line content: data.result.ogTitle,
and am unsure how to properly pass the data into the content: value.
api/post/index.js
import nc from 'next-connect';
import { all } from '@/middlewares/index';
import { getPosts, insertPost } from '@/db/index';
import ogs from 'open-graph-scraper-lite';
const handler = nc();
handler.use(all);
const maxAge = 1 * 24 * 60 * 60;
handler.get(async (req, res) => {
const posts = await getPosts(
req.db,
req.query.from ? new Date(req.query.from) : undefined,
req.query.by,
req.query.limit ? parseInt(req.query.limit, 30) : undefined,
);
if (req.query.from && posts.length > 0) {
res.setHeader('cache-control', `public, max-age=${maxAge}`);
}
res.send({ posts });
});
handler.post(async (req, res) => {
if (!req.user) {
return res.status(401).send('unauthenticated');
}
if (!req.body.source) return res.status(400).send('Please enter the full path of the url');
const options = { url: req.body.source };
ogs(options).then((data) => {
const { result } = data;
console.log(data.result.ogTitle); //Trying to save this var
});
const post = await insertPost(req.db, {
content: data.result.ogTitle, //Trying to save it to this Key
source: req.body.source,
labels: req.body.labels,
creatorId: req.user._id,
});
return res.json({ post });
});
export default handler;
question from:
https://stackoverflow.com/questions/65916032/preforming-lookup-on-form-data-before-saving-to-mongodb-database 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…