我的用户架构中有一个称为产品的数组。我想按ID查找并修改该数组的索引。我不想推或拉,只需为现有数组设置新值。我的代码没有返回任何错误,但也无法正常工作。
//My User Schema with Porducts array
const mongoose = require('mongoose');
const ProdcutSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
productDescription:{
type: String,
required: true
},
pricePerUnit:{
type: Number,
required: true
},
productAmmount:{
type:Number,
required: true
},
/*productImagePath:{
type:String,
required: true
}*/
});
const UserSchema = new mongoose.Schema({
name:{
type: String,
},
email:{
type: String,
},
password:{
type: String,
},
date:{
type: Date,
default: Date.now
},
products:[ProdcutSchema]
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
//My operation on that array
User.findByIdAndUpdate(
'5d2b99652ef5ed2e781ebb68',
{ $set:{products: {
name:product_name,
productDescription: product_Description,
pricePerUnit: price_PerUnit,
productAmmount: product_Ammount
} }},
(err) => {
if (err) console.log(err);
})
请注意,我不能简单地使用User.products.findByIdAndUpdate