mongoose添加新的属性-nodejs

做开发的难免要对某个document添加多个新的属性,

虽然心里吐槽怎么一开始没说,但没办法,需要要的。


例如在用户表里面,居然没有用户的 创建时间 这个属性。

为了添加多一个属性,这里看了下mongoose的介绍,简单说下

消息来源:

http://mongoosejs.com/docs/guide.html

Defining your schema

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs:  Number
  }
});

If you want to add additional keys later, use the Schema#add method.

就是在这个页面找到了这个add方法,不小心都错过了。。

找了好久。。吭啊。


点击后调整到下面这个地址:

http://mongoosejs.com/docs/api.html#schema_Schema-add

他的介绍是:

Schema#add(objprefix)

Adds key path / schema type pairs to this schema.

Parameters:
Example:
var ToySchema = new Schema;
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
show code
Schema.prototype.add = function add (obj, prefix) {
  prefix = prefix || '';
  var keys = Object.keys(obj);

  for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];

    if (null == obj[key]) {
      throw new TypeError('Invalid value for schema path `'+ prefix + key +'`');
    }

    if (Array.isArray(obj[key]) && obj[key].length === 1 && null == obj[key][0]) {
      throw new TypeError('Invalid value for schema Array path `'+ prefix + key +'`');
    }

    if (utils.isObject(obj[key]) && (!obj[key].constructor || 'Object' == utils.getFunctionName(obj[key].constructor)) && (!obj[key].type || obj[key].type.type)) {
      if (Object.keys(obj[key]).length) {
        // nested object { last: { name: String }}
        this.nested[prefix + key] = true;
        this.add(obj[key], prefix + key + '.');
      } else {
        this.path(prefix + key, obj[key]); // mixed type
      }
    } else {
      this.path(prefix + key, obj[key]);
    }
  }
};
  
  


希望你看得懂,我就帮你到这了。不想改就删了表重建一个。哈哈

最后告诉个好消息,当你定义好模式,觉得少了个date属性时候,只要直接加上去就好了。

这样新的document就会有这个新的属性啦。

哈哈,只是旧的会没有,如果需要的话,你还是得手动的去滚一遍,把他添加上去。


var Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;

var User = new Schema({
    email: {type: String, required: true, trim: true},
    pswd: {type: String , required: true, trim: true},
    token:String,
    date:{type: Number , required: true, trim: true}
});

module.exports = mongoose.model('User', User);


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值