gpt4 book ai didi

node.js - 重命名 Mongoose 中的字段

转载 作者:行者123 更新时间:2023-12-03 04:04:04 28 4
gpt4 key购买 nike

我有两个 JSON 对象,每个对象都有一个名字字段。我想将firstname重命名为name,还想使用mongoose将现有的firstname值导入到name。

架构:

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

关于node.js - 重命名 Mongoose 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53447156/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com