最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin18浏览0评论

控制台试图在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
});
发布评论

评论列表(0)

  1. 暂无评论