Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created September 28, 2012 18:34
Show Gist options
  • Save aheckmann/3801422 to your computer and use it in GitHub Desktop.
Save aheckmann/3801422 to your computer and use it in GitHub Desktop.
default_doc_array
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var assert = require('assert')
console.log('\n===========');
console.log(' mongoose version: %s', mongoose.version);
console.log('========\n\n');
var dbname = 'testing_gg-1351c8470075b095';
console.log('dbname: %s', dbname);
mongoose.connect('localhost', dbname);
mongoose.connection.on('error', function () {
console.error('connection error', arguments);
});
var docs = new Schema({ name: String });
var schema = new Schema({
name: String
, docs: { type: [docs], default: function () {
// need to manaually add the ObjectId in this case
return [{ name: 20, _id: new mongoose.Types.ObjectId }]
}}
});
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
var a = new A({ name: 'gg-1351c8470075b095' });
console.log(a);
a.docs.push({ name: 'yup' });
a.save(function (err, a) {
if (err) return done(err);
A.findById(a, function (err, doc) {
console.error('found', doc);
done(err);
});
})
});
function done (err) {
if (err) console.error(err.stack);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
}
@egorvoronov
Copy link

Great! Thank you!!!

Solution for roles if you need default role object for nested array. Based on the above:

// Role.model.js
const roleSchema = new mongoose.Schema({
  name: {
    type: String,
    enum: [ 'admin', 'user' ],
    default: 'user'
  },
  approved: Boolean
}, { _id: false });

// User.model.js
var schema = new mongoose.Schema({
  firstname: {
    type: String
  },
  lastname: {
    type: String
  },
  roles: { type: [roleSchema], default: function () {
    var role = new Role();
    return [role.toObject()];
  }}
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment