0
votes

I am trying to update the documents with the new field name which needs to be combination of firstName and lastName from the same document. I have written a snippet here and trying to update values in the database. It's not getting updated, there are no errors. I have tried to cast _id to ObjectId, But it didn't work.

MongoDB: 3.4 Mongoose: 4.11.x

const mongoose = require('mongoose')
const User = require('./models/user')

mongoose.connect('mongodb://localhost:27017/db', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
})

const users = User.find({}, function(error, doc){
    doc.forEach(function(raw_doc){
        if(raw_doc.firstName) {
            firstName = raw_doc.firstName
        }else{
            firstName = ''
        }
        if(raw_doc.lastName) {
            lastName = raw_doc.lastName
        }else{
            lastName = ''
        }
        name = firstName + " " + lastName
        const user_update = User.findByIdAndUpdate(raw_doc._id, { name: name }, function(error, res) {
            if (error){
                console.log(error)
            }else{
                console.log(res)
            }
        });
    });
});
1
what did you get any error or how did you say not able to update DB, are you saying from console.log(res) ?whoami - fakeFaceTrueSoul
I am simply running this code, It should update the entries in db right? but it's not doing it.Viraj
what did you get here : console.log(res) ?whoami - fakeFaceTrueSoul
getting the documents back with no change. I have set {new:true} but it is not updating the value of name field. I have cross-checked in the database, But the field is not updated.Viraj
I have a feeling the issue is coming from the foreach loop. You might need to use some form of asynchronous programming to make it work.Richard Lovell

1 Answers

0
votes

Please try this :

async function dBConnection() {

    try {
        let dbOp = await Users.find({}).lean(true);
        if (dbOp.length) {
            for (const i of dbOp) {
               const firstName = (i.firstName && (i.firstName).length) ? i.firstName : '';
               const lastName = (i.lastName && (i.lastName).length) ? i.lastName : '';
               const name = firstName + " " + lastName;
               const resp = await Users.findByIdAndUpdate(i._id, { name: name }, { new: true })
                console.log(i._id, '::', resp)
            }
            db.close()
        } else {
            console.log('No users found')
            db.close()
        }
    } catch (error) {
        console.log('Error in DB Op ::', error);
        db.close()
    }
}

module.exports = dBConnection();