控制台试图在MongoDB数据库中保存数据时返回null

编程入门 行业动态 更新时间:2024-10-08 20:35:32

<a href=https://www.elefans.com/category/jswz/34/1771374.html style=控制台试图在MongoDB数据库中保存数据时返回null"/>

控制台试图在MongoDB数据库中保存数据时返回null

我正在Node和Express中编写REST API以报告垃圾邮件用户。当我在Postman中点击API时,我将得到类似{} null的输出。我可以在邮递员中查看状态和消息。我检查了我的本地MongoDB数据库。集合中没有任何内容。

app.post('/reportSpam', async(req, res) => {
  try {
    console.log(req.body);
    let {
      profileID,
      time,
      type,
      message,
      status,
      count,
    } = req.body;
    const data = await spamModel.findOneAndUpdate({
      profileID,
      time,
      type,
      message,
      status,
      count
    }, {
      upsert: true,
      new: true
    });
    console.log(data);
    return res.status(200).send(apiResponse.sendReply(1, 'Added spam data', data));
  } catch (e) {
    console.log(e)
    apiResponse.reportError(e)
    return res.status(500).send(apiResponse.sendReply(0, 'error adding data', e))
  }
})
回答如下:

findOneAndUpdate第一个参数是过滤器,因为您将更新对象作为第一个参数传递,因此将过滤器作为第一个参数传递,如下所示:

const data = await spamModel.findOneAndUpdate(
  {
    profileID: profileID //todo: change the filter as your requirement
  }, 
  {
  profileID,
  time,
  type,
  message,
  status,
  count
}, {
  upsert: true,
  new: true
});

或者如果您每次都想创建一个新文档,也可以使用create这样的方法:

const data = await spamModel.create({
  profileID,
  time,
  type,
  message,
  status,
  count
});

更多推荐

控制台试图在MongoDB数据库中保存数据时返回null

本文发布于:2024-05-07 10:33:23,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   数据库中   数据   null   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!