Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

node.js - Mongoose updateMany by manipulating data before saving each item

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);
      }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
      }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...