Node.js 如何将值推入对象';猫鼬的动态属性?
我想根据使用mongoose从前端接收到的属性值将该值推送到数组中 模式:Node.js 如何将值推入对象';猫鼬的动态属性?,node.js,mongodb,mongoose,nosql,push,Node.js,Mongodb,Mongoose,Nosql,Push,我想根据使用mongoose从前端接收到的属性值将该值推送到数组中 模式: authencity: { fake: [], notSure: [], authentic: [], } 现在,我想根据从前端接收到的属性值将该值推送到数组中 const result = await News.findOneAndUpdate({ name: newsName }, { $push: { `authencity[${authencityTy
authencity: {
fake: [],
notSure: [],
authentic: [],
}
现在,我想根据从前端接收到的属性值将该值推送到数组中
const result = await News.findOneAndUpdate({ name: newsName }, { $push: { `authencity[${authencityType}]`: email } });
AuthentityType可以是fake、notSure、authentic之类的任何类型。基于此值,我想将该值插入相应的数组中
样本数据:
Sample Document :{
"_id": {
"$oid": "5f0af1e09a724b06c86bfaec"
},
"authencity": {
"fake": [],
"notSure": [],
"authentic": []
},
"name": "Rajasthan deputy CM Sachin Pilot\u2019s supporters come to Gurugram resort, call police summon a joke",
"description": "",
"url": "https://news.google.com/__i/rss/rd/articles/CBMiqwFodHRwczovL3d3dy5oaW5kdXN0YW50aW1lcy5jb20vaW5kaWEtbmV3cy9yYWphc3RoYW4tZGVwdXR5LWNtLXNhY2hpbi1waWxvdC1zLXN1cHBvcnRlcnMtY29tZS10by1ndXJ1Z3JhbS1yZXNvcnQtY2FsbC1wb2xpY2Utc3VtbW9uLWEtam9rZS9zdG9yeS1ZQ1BQVDFlandtb1RoQXJaRXVabmNOLmh0bWzSAa0BaHR0cHM6Ly9tLmhpbmR1c3RhbnRpbWVzLmNvbS9pbmRpYS1uZXdzL3JhamFzdGhhbi1kZXB1dHktY20tc2FjaGluLXBpbG90LXMtc3VwcG9ydGVycy1jb21lLXRvLWd1cnVncmFtLXJlc29ydC1jYWxsLXBvbGljZS1zdW1tb24tYS1qb2tlL3N0b3J5LVlDUFBUMWVqd21vVGhBclpFdVpuY05fYW1wLmh0bWw?oc=5",
"category": "general",
"language": "en",
"country": "in",
"__v": 0
}
收到的数据:电子邮件:abcd@gmail.comAuthentityType可能是假的、不确定的或真实的
我想根据收到的AuthentityType推送特定数组中的值您需要使用以下内容定义路径,而不是使用方括号:
`authencity.${authencityType}`
例如authenticity.fake
尝试:
还要注意,在mongoose的findOneAndUpdate版本中,您需要传递参数才能返回修改过的文档
const newColumn = `authencity.${authencityType}`;
const result = await News.findOneAndUpdate({ name: newsName }, { $push: { [newColumn]: email } }, { new: true });
在这里,我创建了一个动态字符串,使用template literal构造一个列名,然后用[]将其括起来,所以mongo会考虑这个栏名 @ AdityaVyas,你能展示一个样例文档和你想要更新的数据吗?@ AdityaVyas,你正在构建基于“代码>新闻名< /Cord>”的查询,但是你说有效载荷只包含代码>电子邮件< /代码>。对吗?
newName
我从params获取。您能通过newName
找到您的文档吗?<代码>结果< /代码>的值是什么?是的,它的完整文档文件考虑了解释您的代码和它将如何帮助,以便其他人可以从中受益。
const newColumn = `authencity.${authencityType}`;
const result = await News.findOneAndUpdate({ name: newsName }, { $push: { [newColumn]: email } }, { new: true });