重命名猫鼬中的字段

Har*_*esh 6 database rest mongodb node.js

我有两个 JSON 对象,每个对象都有一个 firstname 字段。我想将 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)
Run Code Online (Sandbox Code Playgroud)

数据样本:

_id: "5bf5fbef16a06667027eecc2", firstname: "Hareesh", lastname: "Pitchikala", username: "123", password: "123", user_type: "employer", __v: 0
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 18

首先,您需要添加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 },
});
Run Code Online (Sandbox Code Playgroud)

现在,在您的应用程序代码中,您需要运行以下代码:

User.updateMany({}, { $rename: { firstname: 'name' } }, { multi: true }, function(err, blocks) {
    if(err) { throw err; }
    console.log('done!');
});
Run Code Online (Sandbox Code Playgroud)

现在,您可以firstname根据需要从架构中删除。

  • `{ multi: true }` 将被忽略。来自文档:“...MongoDB 将更新与过滤器 [...] 匹配的所有文档,无论 multi 选项的值如何。” (3认同)
  • 不确定,但我必须在代码片段中添加“strict:false”才能使其正常工作:它还说“DeprecationWarning:collection.update已被弃用”。使用 updateOne、updateMany 或bulkWrite 来代替。` 所以我使用了 `upadateMany` 完整代码: ``` User.updateMany( {}, { $rename: { firstname: 'name' } }, { multi: true, strict: false } , function (error) { if (error) { throw error; } console.log('完成!'); } ); ```` (2认同)