保存到Mongoose时如何自动设置密钥名称?

Sha*_*oon 1 mongoose mongodb node.js

我有一个对象:

{ SKU: 'TR1234',
  Description: 'Item 1',
  UoM: 'each',
  client_id: '531382e3005fe0c926bd3957',
  Meta: { Test: 'test1', Image: 'http://www.aol.com' } }
Run Code Online (Sandbox Code Playgroud)

鉴于我的架构,我正在尝试保存它:

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});
Run Code Online (Sandbox Code Playgroud)

但它没有保存,我认为这是因为大写的密钥名称.但是,这些是从CSV动态生成的,用https://github.com/Keyang/node-csvtojson解析

想法?

tim*_*per 6

You can also just use a setter in your mongoose schema, like that:

function toLower (v) {
    return v.toLowerCase();
}

var UserSchema = new Schema({
    email: { type: String, set: toLower } 
});
Run Code Online (Sandbox Code Playgroud)

Just apply it to your fields.

There is also one more approach, just:
email   : { type: String, lowercase: true }
Run Code Online (Sandbox Code Playgroud)

更新密钥: 如果您想更改密钥,您应该使用类似于下面提到的“ecdeveloper”的方法。我的答案是价值,因此将这种声誉赋予“ecdeveloper”是有意义的。抱歉造成混淆。

这是另一种无需创建新对象的方法:

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


ecd*_*per 5

如何在对象的每个键上调用toLowerCase(),并使用小写键构建一个新对象?

// 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
Run Code Online (Sandbox Code Playgroud)