有条件地更新猫鼬查询中的项目

cna*_*ak2 0 mongoose mongodb node.js express

我有以下代码,我正在尝试做两件事。首先,我想让查询具有一个条件,即它在文档中找到“ originator”值,但是如果发现“ owner_id”与原始发件人相同,则不更新第二个参数。

我要执行的第二部分操作仅是设置/更新要传入的字段。我可以使用三元语句吗,如下所示?

  Contacts.update(
    {
      'originator': profile.owner_id,
      'owner_id': !profile.owner_id
    }, 
    {
      $set: {
        (phoneNumber) ? ('shared.phones.$.phone_number': phoneNumber):null,
        (emailAddress) ? ('shared.emails.$.email_address': emailAddress):null
      }
    }, 
    {
      'multi': true
    },
    function(err) {
      err === null ? console.log('No errors phone updated for contacts.shared') : console.log('Error: ', err);
    }
  ) 
Run Code Online (Sandbox Code Playgroud)

Nei*_*unn 7

您的意思是这样的:

var updateBlock = {};
if (phoneNumber)
  updateBlock['shared.phones.$.phone_number'] = phoneNumber;
if (emailAddress)
  updateBlock['shared.email.$.email_address'] = emailAddress;

Contacts.updateMany(
  { 
    "originator": profile.owner_id
    "owner_id": { "$ne": profile.owner_id }
  },
  { "$set": updateBlock },
  function(err, numAffected) {
     // work with callback
  }
)
Run Code Online (Sandbox Code Playgroud)

同你的两个“主”在这里的“不平等”查询条件中要求的误解$ne运营商,不是!JavaScript表达式。MongoDB在这里不使用JavaScript表达式作为查询条件。

第二个“主要”误解是带有条件键的“更新块”的构造。相反,这是一个“ JavaScript对象”,您可以单独构造该JavaScript对象,以便仅指定要实现的键。

但是,仍然存在一个问题,您想使用位置$运算符。假设您实际上在文档中具有“数组”,如下所示:

{
   "originator": "Bill",
   "owner_id": "Ted",
   "shared": {
     "phones": [ "5555 5555", "4444 4444" ],
     "email": [ "bill@stalyns.org", "bill@example.com" ]
   }
}
Run Code Online (Sandbox Code Playgroud)

那么您的“双重”新问题是:

  1. 必须指定一个与数组元素“在查询块中”匹配的查询条件,以便获取要更新的“匹配位置”。

  2. 只能通过使用位置运算符来返回一个匹配的数组索引,而不能像更新此类文档所固有的那样返回两个$

由于这些原因(以及其他原因),强烈建议不要在单个文档中包含“多个数组”。更好的方法是使用“单个”数组,并使用属性来表示列表项实际包含的条目“类型”:

{
   "originator": "Bill",
   "owner_id": "Ted",
   "shared": [
     { "type": "phone", "value": "5555 5555" },
     { "type": "phone", "value": "4444 4444" },
     { "type": "email", "value": "bill@stalyns.org" },
     { "type": "email", "value": "bill@example.com" }
   ]
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您实际上可以解决要在其中进行更新的“匹配”元素:

// phoneNumberMatch = "4444 4444";
// phoneNumber = "7777 7777";
// emailAddress = null;            // don't want this one
// emailAddressMatch = null;       // or this one
// profile = { owner_id: "Bill" };

var query = {
  "originator": profile.owner_id,
  "owner_id": { "$ne": profile.owner_id },
  "shared": {
    "$elemMatch": {
      "type": (phoneNumber) ? "phone" : "email",
      "value": (phoneNumber) ? phoneNumberMatch : emailAddressMatch
    }
  }
};

var updateBlock = {
  "$set": {
    "shared.$.value": (phoneNumber) ? phoneNumber : emailAddress
  }
};

Contacts.updateMany(query, updateBlock, function(err, numAffected) {
  // work with callback
})
Run Code Online (Sandbox Code Playgroud)

在这种情况下,通过“二进制”选择,您就可以在构造中使用三元条件,因为您不必依赖构造中的“命名键”

如果要组合使用“一个或两个,或者两个都提供”的值,则需要更高级的语句:

// phoneNumberMatch = "5555 5555";
// phoneNumber = "7777 7777";
// emailAddress = "bill@nomail.com";
// emailAddressMatch = "bill@example.com";
// profile = { owner_id: "Bill" };

var query = {
  "originator": profile.owner_id,
  "owner_id": { "$ne": profile.owner_id },
  "$or": []
};

var updateBlock = { "$set": {} };
var arrayFilters = [];

if (phoneNumber) {
  // Add $or condition for document match
  query.$or.push(
    {
      "shared.type": "phone",
      "shared.value": phoneNumberMatch
    }
  );

  // Add update statement with named identifier
  updateBlock.$set['shared.$[phone].value'] = phoneNumber;

  // Add filter condition for named identifier
  arrayFilters.push({
    "phone.type": "phone",
    "phone.value": phoneNumberMatch
  })
}

if (emailAddress) {
  // Add $or condition for document match
  query.$or.push(
    {
      "shared.type": "email",
      "shared.value": emailAddressMatch
    }
  );

  // Add update statement with named identifier
  updateBlock.$set['shared.$[email].value'] = emailAddress;

  // Add filter condition for named identifier
  arrayFilters.push({
    "email.type": "email",
    "email.value": emailAddressMatch
  })
}

Contacts.updateMany(query, updateBlock, arrayFilters, function(err, numAffected) {
  // work with callback
})
Run Code Online (Sandbox Code Playgroud)

当然要注意的是,为了在单个update语句中实现多个数组元素,需要使用 MongoDB 3.6及更高版本的位置过滤$[<identifier>]语法。

我最初在文档中使用“多个”数组而不是在“单个”数组上的命名属性来描述的“原始”结构也是如此,如上面的示例所述:

var query = {
  "originator": "Bill",
  "owner_id": { "$ne": "Bill" },
  "$or": []
};

var updateBlock = { "$set": {} };
var arrayFilters = [];

if (phoneNumber) {
  query.$or.push({
    "shared.phones": phoneNumberMatch
  });

  updateBlock.$set['shared.phones.$[phone]'] = phoneNumber;

  arrayFilters.push({
    "phone": phoneNumberMatch
  });
}

if (emailAddress) {
  query.$or.push({
    "shared.email": emailAddressMatch
  });

  updateBlock.$set['shared.email.$[email]'] = emailAddress;

  arrayFilters.push({
    "email": emailAddressMatch
  });
}

Contacts.updateMany(query, updateBlock, arrayFilters, function(err, numAffected) {
  // work with callback
})
Run Code Online (Sandbox Code Playgroud)

当然,如果您根本没有数组(发布的问题缺少任何示例文档),则甚至不需要任何形式的位置匹配,但是您仍然可以通过构造代码块“有条件地”构造JavaScript对象“键” 。您不能以类似JSON的方式“有条件地”指定“键”。