2

Well I want to do some basic error handling and return the _id of the bad insert.

When I am in mongo console and try to insert a duplicate document, then this error is thrown:

> db.users.insertOne({ firstname: "", lastname: "" })
2020-04-27T21:27:55.958+0200 E  QUERY    [js] WriteError({
        "index" : 0,
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: clay.users index: lastname_1_firstname_1 dup key: { lastname: \"\", firstname: \"\" }",
        "op" : {
                "_id" : ObjectId("5ea7323b70f6a7fdfba31e24"),
                "firstname" : "",
                "lastname" : ""
        }
})

A very clear duplicate error, with the faulty "op" and the responding _id. When I am doing this with the mongo nodejs driver, I can only get this error:

driver: true,
  name: 'MongoError',
  index: 0,
  code: 11000,
  keyPattern: { lastname: 1, firstname: 1 },
  keyValue: { lastname: 'Moon', firstname: 'Sania' },
  errmsg: 'E11000 duplicate key error collection: clay.users index: lastname_1_firstname_1 dup key: { lastname: "Moon", firstname: "Sania" }',
  [Symbol(mongoErrorContextSymbol)]: {}

I can check for the error code and stuff, but cant access the "op" property with the faulty "_id" for handling. It would benefit my error handling and code greatly if I could access the faulty "_id". Kind regards

prasad_
  • 12,755
  • 2
  • 24
  • 36
Baesm
  • 83
  • 9
  • do you have an index on firstname or lastname fields? – Morta1 Apr 27 '20 at 19:48
  • @Morta1 on both, I did `db.users.createIndex( { lastname: 1, firstname: 1 }, { unique: true } )`, so its a combined duplicate key – Baesm Apr 27 '20 at 19:59
  • so maybe you already have an object that looks like this `{firstname: "", lastname: ""}` an empty string is also a unique value. – Morta1 Apr 27 '20 at 20:02
  • 2
    @Morta1 yes, thats true. I am not asking why the error is thrown, only asking why I get different error responses in the console and on the nodejs driver. I would love to have the field `error.op._id` in my error message in nodejs. – Baesm Apr 27 '20 at 20:06
  • _"... I would love to have the field error.op._id in my error message in nodejs."_ What is it you want to do with that value (please explain)? – prasad_ Apr 28 '20 at 03:54
  • 1
    @prasad_ To use it as a foreign key for example. For example a student has courses and is able to create a new one called "math" and it is inserted into mongodb. Now a second student wants to create "math" but the unique key does not allow it and so instead he should get the id of the existing math course so I can connect it with him – Baesm Apr 28 '20 at 05:45
  • You can use the _unique_ `keyValue: { lastname: 'Moon', firstname: 'Sania' }` (from the error) to query the same document. – prasad_ Apr 28 '20 at 05:51
  • 1
    @prasad_ yes, thats what I was thinking as well. Will generate a bit of a overhead, but will work I guess. Thanks for your help. – Baesm Apr 28 '20 at 05:53

0 Answers0