Reputation: 238
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)
}
});
});
});
Upvotes: 0
Views: 464
Reputation: 17915
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();
Upvotes: 0