【问题标题】:Submit Data in mongoDB在 mongoDB 中提交数据
【发布时间】:2021-08-29 13:43:07
【问题描述】:

我正在尝试在我的 NEXT 应用程序中使用 mongoose 提交我的数据,我可以使用 getServerSideProps 之类的方法获取数据

export async function getServerSideProps(context) {
  const data = await shop.findOne({ shopName: "testing" });

  return {
    props: {
      dbData: JSON.stringify(data),
    }, // will be passed to the page component as props
  };
} 

现在我想将一些数据放入我的 mongoDb 中,是否有任何方法可以在我的按钮单击后运行并呈现服务器端代码,就像我可以运行我的 mongoose 查询的 getServerSideProps 一样?

【问题讨论】:

    标签: mongodb mongoose next.js


    【解决方案1】:

    在您的 api 控制器中尝试这种方式

    const handler = nextConnect();
    
    //Shop Schema
    const Shop = mongoose.model('Shop',{ 
        shopName: String,
        id: String  
    });
    
    //Post request handeler
    handler.post(async (req, res) => {
      var shop = new Shop({ 
            shopName: req.body.name, 
            id:req.body.id 
       }) 
      let data = await shop.save();
      res.json({message: 'ok'});
    })
    
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2011-07-07
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多