【问题标题】:Object not being added to Mongodb collection, sometimes对象未添加到 Mongodb 集合中,有时
【发布时间】:2019-01-17 11:59:18
【问题描述】:

我有一些其他人编写的代码,它是一个 jquery 函数,它采用动态呈现的列表,并且在按钮单击时应该通过 express 将对象提交到 mongo 集合。

该功能在本地工作,在我推送到 heroku 后它对我有用。但是,一位同事一直无法让按钮单击工作,使用 google chrome 或 safari,页面只是刷新并且没有添加对象。我相信我已经重现了这个问题,但仅限于 MS Edge。

这是jquery函数:

function OnAddProxyClick() {
let proxies = [];

const checkboxes = $('.proxy-input:checked');

for (const checkbox of checkboxes) {
  proxies.push({
    proxyTitle: checkbox.getAttribute('data-title'),
    proxyValue: checkbox.getAttribute('data-value'),
    proxyUnit: checkbox.getAttribute('data-unit')
  });
}
//fetch returns a promise, handle it with .then and check the response to do error handling
//otherwise if all goes well we should redirect
const url = window.location.pathname + '/proxies';
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  redirect: 'follow',
  body: JSON.stringify({ proxies: proxies })
}).then(res => {
  if (res.ok) {
    location.reload();
  } else {
    //show an error here if adding proxy doesn't work
    console.log('The proxy wasnt added')
  }
});
}

如果我删除 location.reload 并让页面挂起,正确的对象可以被 console.logged,但不会添加到集合中。

这是快递代码:

router.post("/:id/proxies", async (req, res) => {
let newProxies = [];
for (const proxy of req.body.proxies) {
  newProxies.push({
    proxyTitle: proxy.proxyTitle,
    proxyValue: proxy.proxyValue,
    proxyUnit: proxy.proxyUnit,
  });
}
// Add every new proxy to the project proxies array
const query = { _id: req.params.id };
const update = { $addToSet: { proxies: { $each: newProxies } } };

const project = await Project.findById(query);

//make sure we don't add a duplicate
for (const newProxy of newProxies) {
  let shouldPush = true;
  for (const proxy of project.proxies) {
    if (
      proxy.proxyTitle == newProxy.proxyTitle &&
      proxy.proxyValue == newProxy.proxyValue &&
      proxy.proxyUnit == newProxy.proxyUnit
    ) {
      shouldPush = false;
      break;
    }
  }

  if (shouldPush) {
    // have tried awaiting this
    project.proxies.push(newProxy);
  }
}
await project.save();

res.end();
 }
);

'update' 变量似乎可以检查 mongo 对象是否存在于集合中但未使用(我尝试使用它但没有帮助),我尝试在项目上使用 await。 proxies.push,这也不起作用。我可以在 Edge 工具中找到的唯一错误是与不匹配的标签有关,但这并不能解释为什么它在 chrome 中对我有用,但对我的同事却没有。

如何确保在页面重新加载之前对象已实际添加到集合中?

【问题讨论】:

    标签: jquery mongodb express


    【解决方案1】:

    我觉得你应该把 express 代码改成这样,效率会高很多。

    router.post("/:id/proxies", async (req, res) => {
        // req.body.proxies contains the array that needs to be pushed in the proxies array 
        // addToSet makes sure that the elements are not repeated   
        await Project.findByIdAndUpdate(req.params.id, { $addToSet: { proxies: req.body.proxies } });
        res.end();
    });
    

    【讨论】:

    • 这看起来确实更有效率!唯一的问题是它允许“重复”条目(mongo 生成 id,因此 $addToSet 将始终将对象指定为唯一的),但这不是一个大问题,而且它现在似乎在 Edge 中工作。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多