MongoDB E11000重复键错误集合(重复键错误)

时间:2020-05-17 19:30:22

标签: javascript database mongodb schema

我正在尝试向mongodb中写入一个数组,并且不断出现此错误...

UnhandledPromiseRejection警告:MongoError:E11000重复密钥 错误集合:test.strains索引: id dup键:{_id: ObjectId('5ec18ebc5c7b4f6149499d93')}

添加到数据库

  const upsertStrain = async (strainObj) => {
    const DB_URL =
      "mongodb_url";

    if (mongoose.connection.readyState == 0) {
      mongoose.connect(DB_URL);
    }

    // if this strain exists, update the entry, don't insert
    let conditions = { name: strainObj.name };
    let options = { upsert: true, new: true, setDefaultsOnInsert: true };

    await Strain.findOneAndUpdate(
      conditions,
      strainObj,
      options,
      (err, result) => {
        if (err) throw err;
      }
    );
  };

调用功能

  for(strain of strains) {
    await upsertStrain({
      name: strain.name,
      mood: strain.mood,
      dateCrawled: new Date(),
    });
  }

模式:

let strainSchema = new mongoose.Schema(
  {
    name: {
        type: String,
        sparse: true,
        unique: true
    },
    mood: {
        type: String,
        sparse: true,
        unique: false
    },
    dateCrawled: {
        type: Date,
        sparse: true
    },
  }
);

我要添加的数组看起来像这样...

[
    {
        "name": "Blackberry Hashplant",
        "mood": "Sleepy"
    },
    {
        "name": "Walrus Kush",
        "mood": "Happy"
    },
    {
        "name": "Cherry Cheesecake",
        "mood": "Sleepy"
    },
    {
        "name": "Gorilla Cake",
        "mood": "Hungry"
    },
    {
        "name": "Divorce Cake",
        "mood": ""
    },
    {
        "name": "Biscotti",
        "mood": ""
    },
    {
        "name": "Kush Mints",
        "mood": ""
    },
    {
        "name": "Cookie Dawg",
        "mood": ""
    },
    {
        "name": "Cake Batter",
        "mood": ""
    },
    {
        "name": "Crazy Glue",
        "mood": ""
    },
    {
        "name": "Grapefruit Sour Dream",
        "mood": ""
    },
    {
        "name": "Gelato Cake",
        "mood": ""
    },
    {
        "name": "Garanimals",
        "mood": ""
    }
]

请帮助...在这上面停留了一段时间

0 个答案:

没有答案