Here I want to update 1 field for all elements in an array of objects. How to update that field with only one query without looping and updating each of the elements or scanning the whole database and matching?
My model schema:
let NameCardSchema = mongoose.Schema({
fullname: {
type: String,
required: true
},
occupation: {
type: String,
default: null
},
company: {
type: String,
default: null,
},
position: {
type: String,
default: null,
},
userID: [String] // field to update
});
Sample data:
User:
_id:5b8e4c6a879ac54ee0f30bb3
username:"Duc"
Namecard array:
[
namecard1:
_id:5b9615c6b157af5afc8ce426
occupation:null
company:"KIS"
position:"Developer"
fullname:"Duc Nguyen Trung"
userID:"5b9a173f0749c52b583818ec"
namecard2:
_id:5b96162fb157af5afc8ce428
occupation:null
company:"KIS"
position:"Developer"
fullname:"Hieu Vuong"
userID:"5b9a16700749c52b583818ea"
]
Expected result:
[
namecard1:
_id:5b9615c6b157af5afc8ce426
occupation:null
company:"KIS"
position:"Developer"
fullname:"Duc Nguyen Trung"
userID:"5b9a173f0749c52b583818ec", "5b8e4c6a879ac54ee0f30bb3" // username Duc's ID added
namecard2:
_id:5b96162fb157af5afc8ce428
occupation:null
company:"KIS"
position:"Developer"
fullname:"Hieu Vuong"
userID:"5b9a16700749c52b583818ea", "5b8e4c6a879ac54ee0f30bb3" // username Duc's ID added
]