如何通过mongoose方法更改fieldName +在模式中更改它?

时间:2017-09-15 02:46:17

标签: mongodb mongoose schema

我有这样的架构:

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) { });

或者我在代码中根本不这样做?我从未处理过数据库架构更改,因此我不确定应用架构更改的方式/位置。

2 个答案:

答案 0 :(得分:0)

在Schema和控制器中进行更改,因为您在Schema字段中使用的任何名称也应该与Controller中的名称相符。

例如

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中使用的名称也应该与您将用于控制器的名称相同。

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

答案 1 :(得分:0)

最好将updateMany用作

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

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

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