Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...