【问题标题】:Rename field in mongoose [duplicate]重命名猫鼬中的字段[重复]
【发布时间】:2023-03-14 22:40:01
【问题描述】:

我有两个 JSON 对象,每个对象都有一个名字字段。我想将名字重命名为名字,也想使用猫鼬将现有的名字值导入名字。

架构:

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

【问题讨论】:

  • 这个问题是关于 Mongoose 的,但它被标记为重复并链接到 MongoDB。来吧,不一样的

标签: node.js database mongodb rest


【解决方案1】:

首先,您需要将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

【讨论】:

  • 不确定,但我必须在 sn-p 中添加 strict:false 才能使其正常工作:它还说 DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead. 所以我使用了 upadateMany Fullcode: ``` User.updateMany( { }, { $rename: { firstname: 'name' } }, { multi: true, strict: false }, function (error) { if (error) { throw error; } console.log('done!'); } ); ```
  • { multi: true }将被忽略。来自文档:“...MongoDB 将更新所有匹配过滤器 [...] 的文档,无论 multi 选项的值如何。”
【解决方案2】:

文档可以更新如下:

db.collection.updateMany({},{ $rename: { "firstname": "name" } } );

【讨论】:

  • 这不是using mongoose - 这是 OP 要求的。
  • 它正在使用猫鼬...
  • @TorbenNordtorp db.collection 不是猫鼬语法,它是 MongoDB 驱动程序。
猜你喜欢
  • 2017-10-05
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 2016-09-09
  • 2015-06-27
相关资源
最近更新 更多