我正在尝试使用 NodeJS (NextJS) 更新 MongoDB 中的文档。我目前的代码是:
import connect from "../../util/mongodb";
async function api(req, res) {
if (req.method === "POST") {
const { id } = req.body;
const { name } = req.body;
const { email} = req.body;
const { anything1 } = req.body;
const { anything2 } = req.body;
if (!id) {
res.status(400).json({ "error": "missing id param" });
return;
}
const { db } = await connect();
const update = await db.collection("records_collection").findOneAndUpdate(
{ id },
{
$set: {
name,
email,
anything1,
anything2
}
},
{ returnOriginal: false }
);
res.status(200).json(update);
} else {
res.status(400).json({ "error": "wrong request method" });
}
}
export default api;
一切正常。但我只想将 ID 请求为必填项,对于其他信息,请保留可选。在此代码中,例如传递 id 和 name,其他三个字段(email、anything1 和 nothing2)在文档中将为空。
是否可以在不需要所有文档信息的情况下实现更新并在正文字段为空时忽略?(作为 NodeJS 和 MongoDB 的初学者,我现在想到的唯一方法就是用很多 if 来包围它……)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句