英文:
How to add an id to an array of object when pushing a new object into the array in node
问题
我有一个名为"previousEducation"的数组,最初是空数组,但一旦我将对象推送到数组中,我希望将推送到数组中的每个对象都具有一个对象ID。尽管从我上传的截图中,对象ID同时出现在(1)和(2)中,但我不需要我在(1)中标出的部分,我想要类似于我命名为(2)的部分,其中每个对象都会有一个ID,后面跟着req.body。是否有一种方法可以将req.body推送到数组中并实现这一点。
注意:从我的req.body中解构出的键值对已经变成了我的Body,它们是:
exam: "waec"
subject: "english"
grade: "a1"
year: "2023"
examNo: "com1234"
candidateNo: "waec7676"
identificationNo: "DE89392982"
谢谢。
英文:
I have an array called "previousEducation" which initially was empty array, but once I push an object into the array, I want each object that will be push into the array to have an object id.
Although from the screenshot I uploaded, the object id was in both (1) and (2) but I don't need the aspect where I circled in (1) I want something inform of the one I named (2) where each object will be having an id follow by the req.body. Is there a way I can push req.body into the array and archive that.
Note: the key value pair from my req.body which has been destructured to become myBody are:
exam: "waec"
subject: "english"
grade: "a1"
yera: "2023"
examNo: "com1234"
candidateNo: "waec7676"
identificationNo: "DE89392982"
Thanks.
My code.
const {receivedEmail, ...myBody} = req.body
studentModel.findOneAndUpdate(
{email: req.body.receivedEmail},
{$push: {previousEducation:{ _id: new ObjectId(), myBody}}}
)
.then((response) => {
// console.log(response + 'JWT');
res.send({message: 'O level Result added successfully', status: true, response});
})
}```[![The image screenshot][1]][1]
[1]: https://i.stack.imgur.com/sztiw.png
</details>
# 答案1
**得分**: 1
将你的`myBody`对象展开。当你将它推送到数组时,
在推送到数组时像这样使用展开操作符`...myBody`。
```javascript
const {receivedEmail, ...myBody} = req.body
studentModel.findOneAndUpdate(
{email: req.body.receivedEmail},
{$push: {previousEducation:{ _id: new ObjectId(), ...myBody}}}
)
.then((response) => {
// console.log(response + 'JWT');
res.send({message: 'O level Result added successfully', status: true, response});
})
}
英文:
Spread your myBody Object. When you are pushing it to the array.
Add the spread operator ...myBody
like this when pushing it to the array.
const {receivedEmail, ...myBody} = req.body
studentModel.findOneAndUpdate(
{email: req.body.receivedEmail},
{$push: {previousEducation:{ _id: new ObjectId(), ...myBody}}}
)
.then((response) => {
// console.log(response + 'JWT');
res.send({message: 'O level Result added successfully', status: true, response});
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论