我有一个用于管理产品相关属性的数据库结构:
const AttributeSchema = new Schema({
name: String,
store_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Store',
required: true,
index: true
},
values: [{
"name": String,
"price": Number,
"created_at": {
type: Date,
default: Date.now
},
"updated_at": {
type: Date,
default: Date.now
},
}],
created_at: {
type: Date,
default: Date.now
},
updated_at: {
type: Date,
default: Date.now
},
});
作为值,我有以下内容:
{
"attribute": {
"name": "Size",
"store_id": "62ba2a8eee4b1cb418546cf2",
"values": [
{
"name": "42",
"price": 0,
"_id": "62c36671019adad103c29e4f",
"created_at": "2022-07-04T22:15:13.205Z",
"updated_at": "2022-07-04T22:15:13.205Z"
},
{
"name": "44",
"price": 0,
"_id": "62c36671019adad103c29e50",
"created_at": "2022-07-04T22:15:13.206Z",
"updated_at": "2022-07-04T22:15:13.206Z"
},
{
"name": "46",
"price": 2,
"_id": "62c36671019adad103c29e51",
"created_at": "2022-07-04T22:15:13.206Z",
"updated_at": "2022-07-04T22:15:13.206Z"
},
{
"name": "48",
"price": 5,
"_id": "62c36671019adad103c29e52",
"created_at": "2022-07-04T22:15:13.206Z",
"updated_at": "2022-07-04T22:15:13.206Z"
}
],
"_id": "62c36671019adad103c29e4e",
"created_at": "2022-07-04T22:15:13.206Z",
"updated_at": "2022-07-04T22:15:13.206Z",
"__v": 0
}
}
现在我只想更新values节点
中包含的一个键请求参数为"62c36671019adad103c29e4f";size "42";
{
"name":"Size",
"size_id": "62c36671019adad103c29e4f",
"store_id":"62ba2a8eee4b1cb418546cf2",
"values": [
{"name": "420", "price": 0.00}
]
}
需要执行
const update = {
name: req.body.name,
store_id: req.body.store_id,
values: req.body.values,
updated_at: Date.now(),
}
let doc = await Attribute.findOneAndUpdate(filter, update, {
returnOriginal: false
});
,但它正确地为我更新了所有的值节点,然后用最后一个请求的值替换了所有的值。如何只更新我想要的值?在这种情况下,尺寸是42?
感谢可以使用elemMatch操作符搜索对象数组中的字段。看到链接
db.myCollection.find({
_id: ObjectId("62ba2a8eee4b1cb418546cf2"),
values: {
$elemMatch: {_id: '62c36671019adad103c29e4f'}
}
}, {
$set:{
'values.$.name': '420'
}
});