如何在保存到Mongoose时自动处理键名?

我有一个对象:

{ SKU: 'TR1234', Description: 'Item 1', UoM: 'each', client_id: '531382e3005fe0c926bd3957', Meta: { Test: 'test1', Image: 'http://www.aol.com' } } 

我试图保存它给我的架构:

 var ItemSchema = new Schema({ sku: { type: String, trim: true, }, description: { type: String, trim: true, }, company_id: { type: Schema.ObjectId, ref: 'Client', }, createdOn: { type: Date, default: Date.now }, updatedOn: { type: Date, default: Date.now } }, {versionKey: false}); 

但它不能保存,我认为这是因为大写的关键名字。 但是,这些是从https://github.com/Keyang/node-csvtojsonparsing的CSV中dynamic生成的

想法?

你也可以在你的mongoose模式中使用一个setter,就像这样:

 function toLower (v) { return v.toLowerCase(); } var UserSchema = new Schema({ email: { type: String, set: toLower } }); 

只要把它应用到你的领域。

 There is also one more approach, just: email : { type: String, lowercase: true } 

键更新:如果你想改变键,你应该像下面提到的'ecdeveloper'。 我的答案是价值观,所以把这个声誉给“ecdeveloper”是有道理的。 对不起,让人困惑。

这里是另一种方法,不创build一个新的对象:

 Object.prototype.keysToUpper = function () { var k; for (k in this) { if (this.hasOwnProperty(k)) this[k.toLowerCase()] = this[k]; delete this[k]; } return this; }; 

怎么样在对象的每个键上调用toLowerCase(),并用小写键构build一个新的对象呢?

 // Assumy your object name is obj var newObj = {}; Object.keys(obj).forEach(function(key) { newObj[key.toLowerCase()] = obj[key]; }); // Here you can save your newObj