【发布时间】:2020-11-24 12:37:36
【问题描述】:
我有新数据要插入到我的 array 或 blog 中(我的集合如下所示 - 如下所示):-
{
_id: 0,
// other vars here...,
blog: [
{
_id: 0,
title: 'Article 1'
},
// add new article here
]
}
现在我可以在我的blog array 中添加新的article,代码如下所示:-
const query = {}
const update = { $push: { blog: inputData } }
const options = { upsert: true }
All.updateOne(query, update, options)
.then(result => {
res.redirect(`/article/${result.upsertedId}`) // read MongoDB documentation that I can get the newly inserted data ID by using result.upsertedId
})
.catch(err => res.redirect(`/`)
但我似乎无法将新插入的数据的ID 放入我的集合中。使用result.upsertedId 会返回undefined。根据上面的代码,我需要ID 才能将用户重定向到ID 的新文章页面。
这里的文档告诉它会 return upsertedId updateOne
这是我在 console.log 时得到的 result(里面没有 upsertedId)
【问题讨论】:
标签: arrays mongodb save insert-update upsert