Answer the question
In order to leave comments, you need to log in
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>`) // вывожу ссылку чтобы изменить/дополнить документ
}
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()
}
Answer the question
In order to leave comments, you need to log in
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>`) // вывожу ссылку чтобы изменить/дополнить документ
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question