Skip to content

Instantly share code, notes, and snippets.

@pedronauck
Last active April 23, 2020 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pedronauck/7835af2c707341ce29c5 to your computer and use it in GitHub Desktop.
Save pedronauck/7835af2c707341ce29c5 to your computer and use it in GitHub Desktop.
Model file for mongoose
'use strict';
var mongoose = require('mongoose'),
timestamp = require('timestamp'),
Schema = mongoose.Schema,
ObjectId = Schema.Types.ObjectId;
var ModelSchema = new Schema({
name: { type: String }
});
function validateFunction(value) {
return false;
}
ModelSchema.path('name').required('true',
'Validate message'
);
ModelSchema.path('field').validate(validateFunction,
'Validate message'
);
ModelSchema.plugin(timestamp);
module.exports = mongoose.model('Model', ModelSchema);
/* jshint -W117 */
'use strict';
var _ = require('lodash'),
should = require('should'),
mongoose = require('mongoose'),
Model = require('path/to/model'),
describe('Model: Model', function() {
it('should exist in mongodb', function(done) {
_.has(mongoose.models, 'Model').should.equal(true);
done();
});
describe('#create()', function() {
var id;
before(function(done) {
var model = new Model({
name: 'My Model'
});
model.save(function(err, modelCreated) {
id = modelCreated.id;
done();
});
});
it('should create a new Model', function(done) {
Model.find({}, function(err, models) {
models.length.should.equal(1);
done();
});
});
it('shoud have a timestamp', function(done) {
Model.findOne({_id: id}, function(err, model) {
should.exist(model.createdAt);
should.exist(model.updatedAt);
done();
});
});
});
describe('#validate()', function() {
var model;
before(function(done) {
model = new Model();
done();
});
it('should name be required', function(done) {
model.validate(function(err) {
var errors = err.errors;
should.exist(errors);
errors.name.type.should.equal('required');
done();
});
});
});
});
'use strict';
function timestamp(schema) {
schema.add({
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
schema.pre('save', function(next) {
this.updatedAt = new Date();
next();
});
}
module.exports = timestamp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment