1

I have a mongoose schema which has a field of comments: [String].

When I try to update the schema, I am checking if the value is null or empty by adding the following code into my controller,

if (req.body.comments !== null || req.body.comments !== '') { container.comments.push(req.body.comments) }

container.save() ...

However when I run this code (using postman for testing) and do not provide a value for the comment field, it updates in the database as null in the array.

comments: [String] is in the main schema definition and not part of a suc-document or anything like that.

Would anybody know a way round this issue or why this happens?

1
  • If you do not provide a value comments is undefined, not null. You should check for that case as well. Commented Oct 18, 2017 at 13:11

2 Answers 2

2

Make sure that comments is not undefined, you can handle all cases this way:

if (req.body.comments && req.body.comments !== '') {
  container.comments.push(req.body.comments)
}

That way empty strings, null and undefined values are not added, assuming req.body.comments always comes in as a string.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, your solution helped, it turns out that I had to use the && operator which you have used instead of the || operator which I was using
0

You need to set container.comments as an empty array before you reach your condition statement

container.comments = container.comments || []
if (req.body.comments && req.body.comments !== '') {
  container.comments.push(req.body.comments)
}

this way the data saved on your database will always be an array, regardless of your sending comments on your request or not.

also its worth mentioning that saving an empty array on monggose will result to undefined unless you override it.

edited the example to take consideration if the array is not empty

1 Comment

your solution works but always creates an empty array, checking whether the array already exists before setting it to a new empty array is also workable in my case. thanks alot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.