【问题标题】:Nodejs Mongoose - Check the array object value exists or not, add a new object to array if not existNodejs Mongoose - 检查数组对象值是否存在,如果不存在则将新对象添加到数组中
【发布时间】:2021-02-14 07:06:29
【问题描述】:

我对 nodejs 很陌生。我想在 mongodb 中检查该值是否存在,如果存在,更新链接视图,如果不存在我想将一个对象推送到数组中。谁能帮我写一个语句来检查数据库中是否存在该值?请帮忙

所以这是Admin 架构

{        
  "_id": "67324b2cc6817758118e9557d8",
  "name": "James",
  "__v": 0,
  "affiliatelink": [
    {
      "storeId": 60014d6e7286763490c3543,
      "storeName": white choc,
      "linkview": 1
    }
  ]
}`


这是我当前的代码。

Admin.findById(adminId).then(admin =>{
if(admin){
//if affiliatelink.storeId = storeId(exist)
Admin.update({ _id: adminId, "affiliatelink.storeId": storeId}, {$inc: {"affiliatelink.$.linkview": 1}}, 
 (err, result) => {
    if (err) {
    console.log("error "+err)
    } 
    else {
      //push an object into array
    }

  });
 

我尝试这样做只是为了检查 if else 语句是否有效。但它不起作用。

const res = await Admin.find({"affiliatelink.storeId":storeId; //use async in function definition
console.log(res);
if (check in res) {
  console.log("item is existed")}
else {
  console.log("item is not existed")
}

【问题讨论】:

    标签: node.js mongodb arrayobject


    【解决方案1】:

    在您的第三个代码 sn-p 中,您正在执行查找操作,该操作将返回一个空数组 [],这将被视为 true,因此这就是控件不进入 else 条件的原因。 使用findOne 而不是find(如果storeId 是唯一的),否则只需检查查询响应的长度是否大于或等于0。

    【讨论】:

      猜你喜欢
      • 2014-05-15
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2021-08-30
      相关资源
      最近更新 更多