【问题标题】:How do you change a fieldName via mongoose method + change it in schema?你如何通过猫鼬方法更改字段名+在模式中更改它?
【发布时间】:2018-02-24 03:16:27
【问题描述】:

我有这样的架构:

const StorySchema = new Schema({
    authorId: String,
    title: String,
    longUrl: String,
    shortUrl: String,
    comment: String,
    category: String,
    author: String,
    date: { type: Date, default: Date.now, index: true },
    votes: { type: Number, default: 1, index: true },
});

我想将架构上的投票字段更改为 votesCount,同时我想实际更改架构。

我会在同一个文件中执行这些操作吗?

const StorySchema = new Schema({
    authorId: String,
    title: String,
    longUrl: String,
    shortUrl: String,
    comment: String,
    category: String,
    author: String,
    date: { type: Date, default: Date.now, index: true },
    votesCount: { type: Number, default: 1, index: true },
});

const StoryModel = mongoose.model('story', StorySchema);

StoryModel.update({}, { $rename: { votes: 'votesCount' } }, { multi: true, strict: false }, function(err, blocks) { });

或者我在代码中根本不这样做?我从未处理过数据库架构更改,所以我不确定如何/在何处应用架构更改。

【问题讨论】:

  • 这是一个代码部署问题。要在运行时更改模型上的模式,您需要取消注册当前模型,然后再次注册新的模式更改。如果您所做的只是“将更改部署到生产环境”,那么您应该立即停止程序访问并更新实际数据,然后使用更改后的代码重新启动。

标签: mongodb mongoose schema


【解决方案1】:

在架构和控制器中进行更改,因为您在架构字段中使用的任何名称也应该与控制器中的名称一致。

例如。

const StorySchema = new Schema({

authorId: String,
title: String,
longUrl: String,
shortUrl: String,
comment: String,
category: String,
author: String,
date: { type: Date, default: Date.now, index: true },
votesCount: { type: Number, default: 1, index: true },
});

在你的控制器中

let form = {
            authorId:req.body.*****,
            title:req.body.*****,
            longUrl:req.body.*****,
            shortUrl:req.body.*****,
            comment:req.body.*****,
            category:req.body.*****,
            author:req.body.*****,
            date:req.body.*****,
            votesCount:req.body.*****
        };

注意:我在这里试图说明的要点是,您在 Schema 中使用的名称也应该与您将用于控制器的名称相同。

我希望这能回答你的问题。

【讨论】:

    【解决方案2】:

    最好使用 updateMany 作为

    db.students.updateMany( {}, { $rename: { "nmae": "name" } } )
    

    并在您的控制器中更改或直接将以前的字段名称替换为新的字段名称。

    我的建议是你首先在控制器或你的项目中替换,如果你的项目在生产中运行更新你的新控制器,而不是你使用 $rename 替换字段名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多