Mongodb using dynamic fields with $not

I programming in react, mongodb, nodejs and expressjs. I have a problem that I cannot solve. I would like to use dynamic fields from $not on the server. For example, the server gets the column name from the front and it is supposed to return the number of documents where the text is different from an empty string, i.e. ''. I’ve tried to do something like this(code below), but it doesn’t help.

const query = {};
query[type] = { $not: '' };
User.countDocuments(query, (err, data) => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true, data: data });
});

Answer

You are close, you probably were looking for $ne instead of $not. So changing it to

const query = {};
query[type] = { $ne: '' };

should fix the issue. This would find all documents where the dynamic type field does not equal ''. If you want to do the inverse, i.e. find all documents where the dynamic field equals an empty string, change it to:

query[type] = { $eq: '' };