Skip to content

Instantly share code, notes, and snippets.

var updates = { $unset: { steak: true }, $set: { eggs: 0 } };
Breakfast.update({}, updates, callback);
var updates = { $unset: { steak: true }, $set: { eggs: 0 } };
// Note the `runValidators` option
Breakfast.update({}, updates, { runValidators: true }, function(err) {
console.log(err.errors['steak'].message);
console.log(err.errors['eggs'].message);
/*
* The above error messages output:
* "Path `steak` is required."
* "Path `eggs` (0) is less than minimum allowed value (2)."
*/
var updates = { $inc: { eggs: -1 } };
Breakfast.update({}, updates, callback);
var breakfastSchema = new mongoose.Schema({
steak: {
type: String,
required: true,
enum: ['flank', 'ribeye'],
validate: function(v) {
// Woops! `this` is equal to the global object!
if (this.eggs >= 4) {
return v === 'flank';
}
var breakfastSchema = new mongoose.Schema({
steak: {
type: String,
required: true,
enum: ['flank', 'ribeye'],
},
eggs: {
type: Number,
required: true,
min: 2
/*
* Any schema with this plugin will run validators on
* `findOneAndUpdate()` by default.
*/
var runValidatorsPlugin = function(schema, options) {
schema.pre('findOneAndUpdate', function(next) {
this.options.runValidators = true;
next();
});
};
var personSchema = new mongoose.Schema({
name: String
});
var bandSchema = new mongoose.Schema({
name: String,
lead: { type: mongoose.Schema.Types.ObjectId, ref: 'person' }
});
var Person = mongoose.model('person', personSchema, 'people');
Band.
findOne({ name: "Guns N' Roses" }).
populate('lead').
exec(function(err, band) {
console.log(band.lead.name); // "Axl Rose"
});
var bandSchema = new mongoose.Schema({
name: String,
lead: { type: mongoose.Schema.Types.ObjectId, ref: 'person' }
});
var autoPopulateLead = function(next) {
this.populate('lead');
next();
};
Band.
findOne({ name: "Guns N' Roses" }).
exec(function(err, band) {
console.log(band.lead.name); // "Axl Rose"
});