Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Update multiple documents by array of objects field value in mongoose

Here is my Schema.

 Home = new Schema({
        name: { type: String, required: true},
        description: {type: String},
        administrator: {type : mongoose.Schema.Types.ObjectId, ref: 'User', required: true},

    users: [{ 
        _id: {type : mongoose.Schema.Types.ObjectId, ref: 'User'},
        email: {type: String},
        name: { type: String},
        status: { type: Number}
    }],
    rooms: [Room]


});
module.exports = mongoose.model('Home', Home);

If I want to find a specific user across multiple documents, I could do

Home.find({"users.email": "johnk@gmail.com"},{users:1})

This would return all homes with users.email = johnk@gmail.com

But the user's field is an array.

"users" : [
        {
            "status" : 0,
            "name" : "Yaknow",
            "email" : "yaknow@gmai.com",
            "_id" : ObjectId("5875a42ea469f40c684de385")
        },
        {
            "status" : 1,
            "name" : "johnk",
            "email" : "johnk@gmail.com",
            "_id" : ObjectId("586e31c6ce07af6f891f80fd")
        }
    ]

(this is just from one home, if there are many homes, there will be many arrays like this) So the above query will return each user array of each home the user has email in. My question is, how do I update all instances of that JohnK into JohnKirtster? Using this would update every user in the array's name to JohnKirster

Home.update(query, {users.name: "JohnKirster"})

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use mongodb $ positional operator by setting multi:true

Home.update(
 {"users.name": "johnk"}, //query, you can also query for email
 {$set: {"users.$.name": "JohnKirster"}},
 {"multi": true} //for multiple documents
)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!