giodamelio
giodamelio

Reputation: 5605

Mongoose Middleware modifying to working

I am trying to add a uuid to every model before it is saved. As far as I can tell, my code it right(based on the first example on this page), but the property is not saved.

var mongoose = require("mongoose");
var uuid = require("node-uuid");

var siteSchema = mongoose.Schema({
    email: {
        type: String,
        unique: true,
        sparse: true
    }
});

siteSchema.pre("save", function(next) {
    console.log(this);
    this.uuid = uuid.v4();
    console.log(this);
    next();
});

var siteModel = module.exports = mongoose.model("Site", siteSchema);

Upvotes: 0

Views: 159

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

The property you are trying to save does not exist in the schema, you need to define it or make it not strict.

So one approach to what you are doing:

var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    uuid = require("node-uuid");


mongoose.connect('mongodb://localhost/test');

var demoSchema = new Schema({
  uuid: String,
});

demoSchema.pre("save", function(next) {
  this.uuid = uuid.v4();
  next();
});


var Demo = mongoose.model( "Demo", demoSchema, "demo" );

var demo = new Demo();

demo.save(function(err,demo) {

  console.log( demo );

});

Where there is another field for uuid:

{ __v: 0,
  uuid: 'b55db0de-7b0e-4d15-854c-90bb49bd1463',
  _id: 53b242a760ca971e30a9349c }

Or you could use the mongoose-uuid plugin instead:

var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    uuid = require("mongoose-uuid");


mongoose.connect('mongodb://localhost/test');

var demoSchema = new Schema({},{ _id: false});

demoSchema.plugin(uuid.plugin, "Demo");

var Demo = mongoose.model( "Demo", demoSchema, "demo" );

var demo = new Demo();

demo.save(function(err,demo) {

  console.log( demo );

});

The places the uuid in the _id field:

{ __v: 0, _id: '82bc7a00-00dd-11e4-a63a-4373a4cdbe8c' }

Upvotes: 2

Related Questions