【问题标题】:finding the data === true from an array returning from mongodb从 mongodb 返回的数组中查找数据 === true
【发布时间】:2019-10-18 13:18:56
【问题描述】:

我想在从 mongoose 的 find() 返回时检查 is_reqestor = true。但是在更新同一个文档时,我传递了id,但它必须更新数据。

let filter = {
                is_reqestor: true
             }

  if (!isAdd) {
                filter["_id"] = { "$ne": id };
              }

    userModel.find(filter, function (err, docs) {
                    if (docs.filter(el => console.log(el.is_requestor)).length > 1 || docs.length >= 1 && userObj.is_active === true) {
                        result.error = "Requestor already exists: " + userObj.is_reqestor;
                        console.log("`Requestor already exists", null);
                        let resp = api_respose.getSuccessResponse(process.env.WEB_URI, result);
                        resolve(resp);
                    }

docs 中,我从数组中的 mongo 获取数据,我必须检查该数据 is_reqestor = true 然后 console.log("Reqester exists")

这是我在 find() 之后在docs 的 console.log 上获得的数据

[ { email: 'esample@example.com',
  job_title: '',
  _id: "9374938749",
  department: 'Credit',
  company_heading: 'Example',
  suite: '',
  city: 'D',
  state: 'CA',
  is_reqestor: true,
  is_active: true,
  name: 'Joe doe',
  role: '343434',
  legacy_id: '1323',
  __v: 0 },
  { email: 'd@example.com',
  job_title: '',
  _id: "93744338749",
  department: 'Credit',
  company_heading: 'Example',
  suite: '',
  city: 'D',
  state: 'CA',
  is_reqestor: false,
  is_active: true,
  name: 'Joe doe',
  role: '343434',
  legacy_id: '1323',
  __v: 0 },
  { email: 'd@example.com',
  job_title: '',
  _id: "93743438749",
  department: 'Credit',
  company_heading: 'Example',
  suite: '',
  city: 'D',
  state: 'CA',
  is_reqestor: true,
  is_active: false,
  name: 'Joe doe',
  role: '343434',
  legacy_id: '1323',
  __v: 0 } ]```

【问题讨论】:

  • 为什么不将is_reqestor: true 添加到过滤器中?
  • 补充说,但在添加数据时将is_reqestor" : false 抛出请求者已经存在

标签: javascript node.js reactjs mongodb mongoose


【解决方案1】:

我可能对这个问题感到困惑,但如果您只想过滤掉具有is_requestor: false 的对象,那么过滤函数应该可以工作。

类似:

docs.filter(el => el.is_requestor)

将返回is_requestor: true 所在的对象。如果我错过了这一点,请给我留言,我会看看我是否能想出别的东西。

【讨论】:

  • if (docs.length >= 1) with this add new with is_reqester = false 说它存在并且在这个条件下 if (docs.length > 1) 比在更新时它说它让@987654324 @ = 真
  • 对不起,我没听懂 - 你到底想做什么?如果您正在寻找 is_requestor 为 true 的任何对象,您可以运行上面的代码。您可以检查结果数组的长度以记录请求者存在。
  • 添加你的代码说undefined检查更新的问题
  • 如果你只想输入 if 语句块,如果任何对象包含is_requestor: true,请使用此检查:if (docs.filter(el => console.log(el.is_requestor)).length) { // do whatever
猜你喜欢
  • 2020-09-12
  • 1970-01-01
  • 2020-03-28
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 2014-09-23
相关资源
最近更新 更多