S
S
Stanislav2020-09-10 17:48:10
MongoDB
Stanislav, 2020-09-10 17:48:10

Is it possible to get the ID of a take when saving a document?

I have a collection with a unique field (field)
When saving a record, an error 11000 crashes, everything is fine here, but is it possible to somehow change this error, for example, in the mongoose schema, so that the duplicate ID is indicated along with the error? I need to do in case of a match, change / expand the record, and I have to look for a duplicate either before saving or after trying to save, this is not convenient ...

Now I'm doing a check before saving something like that

function saveCollect(request) {
    return Collect.findOne({field: "слово"}).then(e => {
        return null === e
            ? new Collect({field: "слово"}).save()
            : errorDuplicate(e)
    })
}

function errorDuplicate(request) {
    return throw Error(`<a href="/fields/${request._id}/">дубликат</a>`) // вывожу ссылку чтобы изменить/дополнить документ
}


I would like to make it possible to catch the document ID without crutches above when saving
exports.post = (request, response, next) => {
    const makeRequest = async () => {
        await saveCollect(request.body.field)
        return response.end()
    }
      
    return makeRequest()
        .catch(e => {
            // При коде 11000 хотелось бы видеть ID документа, быть может это можно настроить в схеме монгуса?!
            return errors(403, e.message)
        })
}

function saveCollect(request) {
    return Collect({field: request}).save()
}


I don’t understand at all why this was not done by default, mongo will spit out a duplicate error, but at the same time the message does not carry any semantic load in itself, what kind of double, what double, what document is identical, so you have to make 2 requests instead of one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-09-12
@Che603000

It is indeed impossible to get the document id in error 11000.
On the other hand, the field you are looking for is also a key, since the field is unique. It follows that you can find a document by this field. Alternatively you can do

function errorDuplicate(field) {
    return throw Error(`<a href="/fields/${field}/">дубликат</a>`) // вывожу ссылку чтобы изменить/дополнить документ
}

Although for this, you may have to change the API on the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question