控制台试图在MongoDB数据库中保存数据时返回null
我正在Node和Express中编写REST API以报告垃圾邮件用户。当我在Postman中点击API时,我将得到类似{} null
的输出。我可以在邮递员中查看状态和消息。我检查了我的本地MongoDB数据库。集合中没有任何内容。
app.post('/reportSpam', async(req, res) => {
try {
console.log(req.body);
let {
profileID,
time,
type,
message,
status,
count,
} = req.body;
const data = await spamModel.findOneAndUpdate({
profileID,
time,
type,
message,
status,
count
}, {
upsert: true,
new: true
});
console.log(data);
return res.status(200).send(apiResponse.sendReply(1, 'Added spam data', data));
} catch (e) {
console.log(e)
apiResponse.reportError(e)
return res.status(500).send(apiResponse.sendReply(0, 'error adding data', e))
}
})
回答如下:findOneAndUpdate
第一个参数是过滤器,因为您将更新对象作为第一个参数传递,因此将过滤器作为第一个参数传递,如下所示:
const data = await spamModel.findOneAndUpdate(
{
profileID: profileID //todo: change the filter as your requirement
},
{
profileID,
time,
type,
message,
status,
count
}, {
upsert: true,
new: true
});
或者如果您每次都想创建一个新文档,也可以使用create
这样的方法:
const data = await spamModel.create({
profileID,
time,
type,
message,
status,
count
});
控制台试图在MongoDB数据库中保存数据时返回null
我正在Node和Express中编写REST API以报告垃圾邮件用户。当我在Postman中点击API时,我将得到类似{} null
的输出。我可以在邮递员中查看状态和消息。我检查了我的本地MongoDB数据库。集合中没有任何内容。
app.post('/reportSpam', async(req, res) => {
try {
console.log(req.body);
let {
profileID,
time,
type,
message,
status,
count,
} = req.body;
const data = await spamModel.findOneAndUpdate({
profileID,
time,
type,
message,
status,
count
}, {
upsert: true,
new: true
});
console.log(data);
return res.status(200).send(apiResponse.sendReply(1, 'Added spam data', data));
} catch (e) {
console.log(e)
apiResponse.reportError(e)
return res.status(500).send(apiResponse.sendReply(0, 'error adding data', e))
}
})
回答如下:findOneAndUpdate
第一个参数是过滤器,因为您将更新对象作为第一个参数传递,因此将过滤器作为第一个参数传递,如下所示:
const data = await spamModel.findOneAndUpdate(
{
profileID: profileID //todo: change the filter as your requirement
},
{
profileID,
time,
type,
message,
status,
count
}, {
upsert: true,
new: true
});
或者如果您每次都想创建一个新文档,也可以使用create
这样的方法:
const data = await spamModel.create({
profileID,
time,
type,
message,
status,
count
});
与本文相关的文章
评论列表 (0)
- 暂无评论