简体   繁体   English

MongoDB findOneAndUpdate 不返回错误但也不更新数据库

[英]MongoDB findOneAndUpdate doesn't return errors but also doesn't update the database

I'm trying to use findOneAndUpdate() but can't seem to get it to work.我正在尝试使用 findOneAndUpdate() 但似乎无法让它工作。 Here's the query I'm using.这是我正在使用的查询。 It adds an object to an 'items' array nested inside of a 'lists' array for a particular entry with 'username'.它将 object 添加到嵌套在“列表”数组中的“项目”数组中,用于具有“用户名”的特定条目。 I've tried it with a simple $set for a field not inside of a nested array, and it also doesn't seem to work.我已经为不在嵌套数组内的字段使用简单的 $set 进行了尝试,但它似乎也不起作用。 Currently no errors are being returned.目前没有返回错误。

MongoClient.connect(
      uri,
      { useUnifiedTopology: true },
      (err, db) => {
        if (err) throw err;
        var dbo = db.db("Todolist");
        dbo.collection("Users").findOneAndUpdate(
          {
            username: username,
            lists: {
              $elemMatch: {
                name: listName,
              },
            },
          },
          {
            $push: {
              "lists.$.items": {
                title: title,
                description: description,
                dueDate: dueDate,
                priority: priority,
                completed: false,
              },
            },
          }
        );
      },
      (err, doc) => {
        if (err) res.send("/addListItem failed");
        else res.send("/addListItem successful");
      }
    );
  } catch (e) {
    console.error(e);
  }

You have to use .dot notation along with the $ positional operator here您必须在此处使用.dot符号和$位置运算符

Schema.findOneAndUpdate(
  { username: username },
  { "lists.$.name": listName }
)

It turned out that the answer to my problem was bracket placement.事实证明,我的问题的答案是支架放置。 I placed the callback after the closing ) for the function arguments to findOneAndUpdate .我将 function arguments 的回调(在关闭后)放置到findOneAndUpdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM