简体   繁体   中英

Map function in NodeJS not working as expected

I am trying to migrate some data from an old MongoDB schema to a new one. All the schema stuff is working fine. What I cannot understand is why the old documents are not being converted before being saved as new documents. I am reading all the documents, using a map function to convert them to the new schema then saving them. But they are all failing validation because, it turns out, they haven't been modified to the new schema at all. Is this an async issue? Any clues would be great.

let User = require('./api/models/user.model');

let newUser;
let mapUsers = () => {

    let makeUser = (u) => {
        return {
            firstName: u.first_name,
            lastName: u.last_name,
            avatarUrl: u.avatar_url,
            email: u.email,
            loginCount: u.login_count,
            loginTime: u.login_time,
            logoutTime: u.logout_time
        }
    };
    h2User.find({}).limit(1).exec((err, users) => {
        if (err) {
            console.error(err);
        } else {
            users.map(user => {
                newUser = new User(makeUser(user));  // like this doesn't work
                newUser.save((err, nu) => {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(nu._id)
                    }
                });
            });
        }
    });
};

mapUsers();

You would have to convert the Mongo document into an object with new User(makeUser(user.toObject())) .

As Mongoose returns a document, it will contain other attributes that may not be apparent. When you do console.log(user) it usually prints the output of toObject so it can get confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM