[英]Mongoose: findByIdAndUpdate: Trying to update all documents with name field (firstName + lastName)
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.我正在尝试使用新字段名称更新文档,该名称需要是同一文档中的 firstName 和 lastName 的组合。 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.
我试图将 _id 转换为 ObjectId,但它没有用。
MongoDB: 3.4 Mongoose: 4.11.x MongoDB:3.4 猫鼬: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)
}
});
});
});
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.