Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have seen how mongoose updateMany() can be used to update some fields easily. My question is can updateMany() also be used when you are to manipulate data before updating the database. I have some lines of code here below. Can updateMany be used to implement something similar to this?


    try {
        const userWithObjectLocation = await User.find({zipcode: { $exists: true }});
        userWithObjectLocation.map(async user =>{
          const locationObject = zipcodes.lookup(user.zipcode);
          if(locationObject){
            const location  = `${locationObject.city}, ${locationObject.state}`
            await User.findByIdAndUpdate(user._id, {location})

          }
        })
        return res.status(200).json({message: "Location has been updated successfully"});
      } catch (err) {
        console.log(err);
        return res.status(500).json(err);
      }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

you know that the result await User.find({zipcode: { $exists: true }}) is a Array of Model, so in map, each user is a model...

for your problem don't need to use findByIdAndUpdate

you can try this

    try {
        const userWithObjectLocation = await User.find({zipcode: { $exists: true }});
        userWithObjectLocation.map(async user =>{
          const locationObject = zipcodes.lookup(user.zipcode);
          if(locationObject){
            const location  = `${locationObject.city}, ${locationObject.state}`
            user.location = location;
            await user.save() 

          }
        })
        return res.status(200).json({message: "Location has been updated successfully"});
      } catch (err) {
        console.log(err);
        return res.status(500).json(err);
      }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share

548k questions

547k answers

4 comments

56.5k users

...