Skip to content

Instantly share code, notes, and snippets.

@luccastera
Created November 14, 2011 21:26
Show Gist options
  • Save luccastera/1365234 to your computer and use it in GitHub Desktop.
Save luccastera/1365234 to your computer and use it in GitHub Desktop.
Mongoose validation does not work when using ref
var mongoose = require('mongoose'),
Schema = mongoose.Schema
mongoose.connect('mongodb://localhost/my_database')
// Define User Schema
var UserSchema = new Schema({
name: {type: String}
})
var User = mongoose.model('User', UserSchema)
// Define Comment Schema
var CommentSchema = new Schema({
content: {type:String, required: true},
actor: { type: Schema.ObjectId, ref: 'User', required: true}
})
var Comment = mongoose.model('Comment', CommentSchema)
// The following test passes (REQUIRED on type String)
exports.testContentRequired = function(test) {
test.expect(3)
var user = new User({
name: 'Joe'
})
user.save(function(err, data) {
var comment = new Comment({
actor: user
})
comment.save(function(err, data) {
test.ok(err)
test.equal('Validation failed', err && err.message)
test.ok(err && err.errors.content)
test.done()
})
})
}
// The following test does not pass (Required when using ref)
exports.testActorRequired = function(test) {
test.expect(3)
var user = new User({
name: 'Joe'
})
user.save(function(err, data) {
var comment = new Comment({
content: 'My comment goes here'
})
comment.save(function(err, data) {
test.ok(err)
test.equal('Validation failed', err && err.message)
test.ok(err && err.errors.actor)
test.done()
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment