@Sky020 I want to prevent duplicate records in my database. I tried marking original_url as a unique field but it just gave an error although the short_url which is set to be equal to the number of documents at the time is 1
There’s only one document in the database and it has short_url of 0, but I got a JSON response with the same original_url where the short_url is 1. Is there a way to use Model.find to check if a document with a given URL is already in the database and to not insert a new document if one with that URL is also present?
Sure. This is the whole point of Model.find. Specifically, I would expect you to use Model.findOne. The Mongoose docs are quite helpful for seeing how to use it.
Would there be something in the err object if a document with the given URL is already there? Or is there some other check for it?
Edit: So since the first found document is passed to the callback, couldn’t I just check if it’s a truthy value or not? If it’s truthy, there’s a document with that URL already present. Otherwise there isn’t.
Url.findOne({ original_url: originalUrl }, (err, foundUrl) => {
if (err) {
console.log(err);
}
if (!foundUrl) {
url.save((err, url) => {
if (err) {
console.log(err);
}
});
}
});
I’ll test this out now.
Edit: Yeah, I think it works.
By the way, I get these deprecation warnings in Visual Studio Code’s terminal while the server is running:
(node:11560) DeprecationWarning: Listening to events on the Db class has been deprecated and will be removed in the next major version.
(node:11560) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
These aren’t from my own code but from the implementation, right?
Looks like the only way to remove the warnings is to downgrade MongoDB/Mongoose:
The issue is not with your code, but the fact that Mongoose uses MongoDB, and MongoDB have updated their code, but Mongoose have not made the equivalent update, yet.
Otherwise, the only way to make the warning go away on the latest version would be to edit the mongoose library in the node_modules folder.