标签:
var mongoose = require(‘mongoose‘); mongoose.connect(‘mongodb://localhost/QuestionMaker‘); exports.mongoose = mongoose;
var QuestionSchema = new Schema({ id: String, qtype: Number, name: String, content: String, options: [ { name: String } ], answer: String });
var Question = mongodb.mongoose.model("Question", QuestionSchema);
//保存试题 QuestionDAO.prototype.save = function(obj, callback){ var instance = new Question(obj); instance.save(function(err){ callback(err, null); }); } //更新试题 QuestionDAO.prototype.update = function(obj, callback){ Question.findByIdAndUpdate(obj._id, obj, {}, function(err){ callback(err, null); }); }
var CounterSchema = Schema({ _id: {type: String, required: true}, seq: { type: Number, default: 1 } }); var Counter = mongodb.mongoose.model("Counter", CounterSchema);
QuestionSchema.pre(‘save‘, function(next) { var doc = this; Counter.findByIdAndUpdate({_id: ‘questionid‘}, {$inc: { seq: 1} }, function(error, counter) { if(error) return next(error); doc.id = counter.seq; next(); }); }); QuestionSchema.set(‘toObject‘, { getters: true });
用“MEAN”技术栈开发web应用(三)用mongodb搭建数据库
标签:
原文地址:http://www.cnblogs.com/lvdabao/p/mean-techstack-mongodb.html