Home > OS >  Mongoose model deleteOne() only works with hard coded string
Mongoose model deleteOne() only works with hard coded string

Time:01-22

I have a strange error with mongoose deleteOne() function. Today I wanted to work on my project and got an error while deleting an item from a collection. It simply doesn't delete the document until I use a hardcoded parameter for the options object like this:

const { deletedCount } = await Model.deleteOne({symbol: 'hardcoded'})
// results in deletedCount = 1

But if I try to use a dynamic string like:

const test = 'dynamic'
const { deletedCount } = await Model.deleteOne({symbol: test})
// results in deletedCount = 0

It does no longer delete the document from my collection. The strange thing is yesterday it worked fine and deleted the item.

I tried one other thing I read regarding errors with deleteOne():

const { deletedCount } = await Model.deleteOne({symbol: JSON.stringifiy(symbol)})

But this doesn't work, too.

Does anyone have an idea what's going wrong?

CodePudding user response:

I always default to using ids whenever possible to make sure there's no mistake in the data I am targeting with a given operation. So in this case that would mean using findByIdAndDelete() instead. If I don't know the id of the document I'm trying to delete, then only I'd use findOneAndDelete() or deleteOne(), as you have, with something other than an id to identify the document I'm looking for.

Are you certain that the key-value pair you're passing to the function exists in your database?

CodePudding user response:

Problem solved. I accidentally added an additional space character at the end of the string. This is very strange because the error was there since the beginning of my project and yesterday it worked.

So for everyone who might have a similar problem:

I have a ejs template file where I render a html element like this:

<div id="<%= symbol %> ">

Then in my event handler for requesting the server to deleting one item from my list I use the id attribute as a request parameter in the body. In the route handler this parameter is passed to mongoose:

const { symbol } = req.body
const { deletedCount } = await Model.deleteOne({ symbol })

As I mentioned. In the template file after the last ejs seperator there is an addional space character that caused the error. I spotted this issue by making a copy of the monoogse query and than logged it to the console. There I could see the wrong condition parameter.

  • Related