做开发的难免要对某个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(obj
, prefix
)
Adds key path / schema type pairs to this schema.
Example:
var ToySchema = new Schema;
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
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);