简体   繁体   English

猫鼬在自定义_id上无法正常工作

[英]Mongoose find on custom _id not working

For whatever reason, mongoose seems to be unable to actually locate my document after a find call because of a custom ID. 无论出于何种原因,由于自定义ID,猫鼬在find呼叫后似乎无法实际找到我的文档。

The source of the problem: 问题的根源:

// ...
models.Item.findOne().where({ _id: item.id }).exec((i) => {
  console.log(item.id, i);
  if (!i) i = new models.Item({ _id: item.id, href: item.href, name: item.name });
  // ...

The console just logs the following: 控制台仅记录以下内容:

> 0 null
> MongoError: E110000 duplicate key error index: items.$_id_  dup key: { : 0 }

Indicating it seems to be unable to locate the document with the ID zero, but immediately follows up by complaining the key already exists with a value of 0 when I try to create a new one. 表明它似乎无法找到ID为零的文档,但是当我尝试创建一个新的密钥时,立即抱怨该密钥已经存在,其值为0。

Upon looking at the database, I can clearly see my document with an _id of 0. 查看数据库后,我可以清楚地看到_id为0的文档。

{
  "id": 0,
  // ...
}

And this is the schema I'm using: 这是我正在使用的架构:

const ItemSchema = new mongoose.Schema({
  _id: { type: Number, min: 0, max: 400000, unique: true, required: true },
  // ...
}

I've tried find and findOne in the chained and un-chained versions and findById . 我试过在链式和非链式版本中使用findfindOne以及findById None of them are yeilding the existing document. 他们都没有在编写现有文档。 Why? 为什么?

You're missing the error parameter in your exec callback. 您在exec回调中缺少error参数。 It should be: 它应该是:

models.Item.findOne().where({ _id: item.id }).exec((err, i) => {...

The second parameter is the document result. 第二个参数是文档结果。

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

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