【问题标题】:Mongoose/Node.js : The positional operator did not find the match needed from the queryMongoose/Node.js:位置运算符没有从查询中找到所需的匹配项
【发布时间】:2022-01-06 13:05:45
【问题描述】:

我尝试使用 Mongoose 和 NodeJS 更新 MongoDB 集合,但有时会出现以下错误,但并非总是出现:

MongoServerError: 在 findAndModify :: 期间计划执行程序错误,由 :: 位置运算符未从查询中找到所需的匹配项。

这是我的代码:

NodeJS

try {
  this.myArrayUpdate = { 'description': 'test' };

  this.update = { $set: 
    { 'myArray.$': this.myArrayUpdate }
  };

  const cardId = ObjectId("61d6e320520fac65775a7ba8")

  const userId = ObjectId("61a8e433648e1963ae7358be");

  const filter = { 
    userId: userId,
    'myArray._id': cardId,
  };

  const options = { 
    upsert: true, 
    new: true 
  };

  MyCollection
    .findOneAndUpdate( 
      filter, 
      this.update,
      options,
    )
  .then ( () => {
    return res.status(204).json({ message: 'MyCollection updated ' });
  });
} catch (error) {
  throw error;
}

MongoDB

{
    "_id" : ObjectId("61a8e433648e1963ae7358be"),
    "myArray" : [ 
        {
            "description" : "test",
            "starting" : null,
            "ending" : null,
            "_id" : ObjectId("61d6e320520fac65775a7ba8")
        },
        {
            "description" : "test 2",
            "starting" : null,
            "ending" : null,
            "_id" : ObjectId("61d6e320520fac657812991a")
        },
    ],
}

如果找到答案的一部分,每次我更新我的子文档数组时,_id 都会改变,所以这就是为什么会出现错误,如果我更新我的页面就不会再出现错误了!

是否有可能在更新子文档数组时不创建新的_id?

感谢您的回答,

大卫

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您提供的文档没有userId 字段,因此您的过滤器与文档不匹配。该字段名为_id:

    const filter = { 
        _id: userId,
        'myArray._id': cardId,
      };
    

    另外,更新文档的写入方式,myArray 中的整个匹配元素将被覆盖,但我假设您只想更新description。它看起来像这样:

    this.update = { $set: 
        { 'myArray.$.description': 'test' }
      };
    

    这是updating a document in an array 的示例。这是Mongo playground 中的一个工作示例。

    【讨论】:

    猜你喜欢
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2015-12-23
    • 2013-08-15
    • 2017-11-14
    相关资源
    最近更新 更多