2017-09-15 27 views
0

我有这样一个模式:你如何通过mongoose方法更改fieldName并在模式中更改它?

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

或者我不在代码中这么做?我从来没有处理数据库模式更改,所以我不确定如何/在哪里应用模式更改。

+0

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

回答

0

在架构和控制器中进行更改,因为您在架构字段中使用的任何名称也应该与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.***** 
     }; 

注:主穴想在这里提出的是,这个名字你在架构中使用也应该在相同的名字你的要去使用你的控制器。

我希望这是你的问题的答案。

0

最好使用updateMany作为

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

,并改变你的控制器或直接取代以前的字段名新字段名,其中以往任何时候都可能。

我的建议是更好ü在控制器或您的项目,如果在生产运行项目的更新您的新控制器妳比使用$重命名

相关问题