我有两个 JSON 对象,每个对象都有一个名字字段。我想将名字重命名为名称,还想使用猫鼬将现有的名字值导入到名称。
Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const user = new Schema({
firstname:{ type:String },
lastname:{ type:String },
username:{ type:String },
password:{ type:String },
user_type:{ type:String },
})
module.exports = mongoose.model('user', user)
数据样本:
_id: "5bf5fbef16a06667027eecc2", firstname: "Hareesh", lastname: "Pitchikala", username: "123", password: "123", user_type: "employer", __v: 0
首先,您需要添加name
到你的模式,所以它变成:
const user = new Schema({
name: { type:String },
firstname: { type:String }, //keep this for now
lastname: { type:String },
username: { type:String },
password: { type:String },
user_type: { type:String },
});
现在,在您的应用程序代码中的某个位置,您需要运行以下命令:
User.updateMany({}, { $rename: { firstname: 'name' } }, { multi: true }, function(err, blocks) {
if(err) { throw err; }
console.log('done!');
});
现在,您可以删除firstname
如果您愿意,可以从您的架构中获取。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)