使用 mongoose (MongoDB) 编辑数组中的多个对象
所以我尝试了几种方法,但我不能,我可以使用相同的密钥修改多个对象,但我无法使用不同的密钥修改任何对象,如果有人可以帮助我,这是一个相当复杂的问题
{
id: 123,
"infos": [
{ name: 'Joe', value: 'Disabled', id: 0 },
{ name: 'Adam', value: 'Enabled', id: 0 }
]
};
在我的数据库中,我有一个集合一个数组和其中的几个对象给出了这个。
我想修改这些对象,按它们的名称过滤并修改值。
为了给你一个更好的例子,我的网站返回一个包含新数据的对象,我想用新对象修改数据库对象,而不清除数组,名称键永远不会改变。
const object = [
{ name: 'Joe', value: 'Hey', id: 1 },
{ name: 'Adam', value: 'None', id: 1 }
];
for(const obj in object) {
Schema.findOneAndUpdate({ id: 123 }, {
$set: {
[`infos.${obj}.value`]: "Test"
}
})
}
这段代码可以工作,但没有优化,它会发出多个请求,我想在一个请求中完成所有操作,而且它不会更新 id,只更新值。
如果有人可以帮助我,那就太好了,我到处都找过了,但找不到任何东西
我的架构结构
new Schema({
id: { "type": String, "required": true, "unique": true },
infos: []
})
我使用 $addToSet
方法将对象插入 <代码>信息数组
So I tried several ways, but I can't, I can modify several objects with the same key but I can't modify any with different keys, if anyone can help me is quite a complex problem
{
id: 123,
"infos": [
{ name: 'Joe', value: 'Disabled', id: 0 },
{ name: 'Adam', value: 'Enabled', id: 0 }
]
};
In my database I have a collection with an array and several objects inside which gives this.
I want to modify these objects, filter by their name and modify the value.
To give you a better example, my site returns me an object with the new data, and I want to modify the database object with the new object, without clearing the array, the name key never changes.
const object = [
{ name: 'Joe', value: 'Hey', id: 1 },
{ name: 'Adam', value: 'None', id: 1 }
];
for(const obj in object) {
Schema.findOneAndUpdate({ id: 123 }, {
$set: {
[`infos.${obj}.value`]: "Test"
}
})
}
This code works but it is not optimized, it makes several requests, I would like to do everything in one request, and also it doesn't update the id, only the value.
If anyone can help me that would be great, I've looked everywhere and can't find anything
My schema structure
new Schema({
id: { "type": String, "required": true, "unique": true },
infos: []
})
I use the $addToSet
method to insert objects into the infos
array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
所有位置
$[]
运算符充当数组字段中所有元素的占位符。在
$in
中,您可以使用id的动态数组
。例如:
常量 ID = [1,2,..n]
db.collection.update(
//相同的代码...
{
数组过滤器:[
{
“x.id”:{
$in: id
}
},
],
多:真实
})
MongoPlayGround 链接: https://mongoplayground.net/p/Tuz831lkPqk
Try This :
The all positional
$[]
operator acts as a placeholder for all elements in the array field.In
$in
you can use dynamicarray
of id.Ex :
const ids = [1,2,..n]
db.collection.update(
//Same code as it is...
{
arrayFilters: [
{
"x.id": {
$in: ids
}
},
],
multi: true
})
MongoPlayGround Link : https://mongoplayground.net/p/Tuz831lkPqk
也许您正在寻找这样的内容:
解释:
您为您拥有的对象中的所有名称定义 arrayFilters 并更新值和过滤器。所有文档中的 id ...
游乐场
Maybe you look for something like this:
Explained:
You define arrayFilters for all names in objects you have and update the values & id in all documents ...
playground