gpt4 book ai didi

javascript - 如何停止 mongoose/javascript 向数组添加空值?

转载 作者:行者123 更新时间:2023-11-30 14:59:09 29 4
gpt4 key购买 nike

我有一个 mongoose 模式,它有一个字段 comments: [String]

当我尝试更新架构时,我通过将以下代码添加到我的 Controller 中来检查该值是 null 还是空

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

container.save() ...

但是,当我运行这段代码(使用 postman 进行测试)并且没有为评论字段提供值时,它在数据库中更新为数组中的 null。

comments: [String] 在主模式定义中,而不是 suc-document 或类似文件的一部分。

有人知道解决这个问题的方法或者为什么会这样吗?

最佳答案

确保注释不是undefined,你可以这样处理所有情况:

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

假设 req.body.comments 始终以字符串形式出现,这样就不会添加空字符串、null 和未定义值。

关于javascript - 如何停止 mongoose/javascript 向数组添加空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810972/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com