Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

node.js - Preforming Lookup on form data before saving to MongoDB Database

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...