Ad

Remove Entry That Matches "this Text" From MongoDB

Ok, I've searched, and searched and I've not been able to find a way to make this work. Here's what I have:

I'm working on a chat application in node/express/socketio, etc. I'm trying to create a 'clear' function to remove a certain chat message from MongoDB based on input specified. For example:

/clear badword
/clear heck
/clear Barbara Streisand

I'm struggling to create a proper RegEx that will actually find entries that contain the specified text.

Here's what I'm using currently:

Chat.remove({"msg":{$regex: new RegExp('.*' + myInput, 'i')}});

It just doesn't seem to find anything. Note: The specified text can be anywhere in the chat message, so I need to be able to say:

If <this text> exists anywhere in the msg key, remove it.

I have been looking at RegEx documentation for hours now and I can't make any of it work. Could anyone point me in the right direction?

Ad

Answer

You need to either provide a callback to your remove call, or call exec on the query object it returns to actually execute the remove operation.

So either:

Chat.remove({"msg":{$regex: new RegExp('.*' + myInput, 'i')}}, (err) => {...});

Or

Chat.remove({"msg":{$regex: new RegExp('.*' + myInput, 'i')}}).exec();

One note on your regex: you don't need to add the '.*' prefix.

Ad
source: stackoverflow.com
Ad