默认值

在模式中声明默认值

您的模式可以为某些路径定义默认值。如果您创建新文档时未设置该路径,则默认值将生效。

注意:只有当路径的值严格为undefined时,Mongoose 才会应用默认值。

const schema = new Schema({
  name: String,
  role: { type: String, default: 'guitarist' }
});

const Person = db.model('Person', schema);

const axl = new Person({ name: 'Axl Rose', role: 'singer' });
assert.equal(axl.role, 'singer');

const slash = new Person({ name: 'Slash' });
assert.equal(slash.role, 'guitarist');

const izzy = new Person({ name: 'Izzy', role: undefined });
assert.equal(izzy.role, 'guitarist');

// Defaults do **not** run on `null`, `''`, or value other than `undefined`.
const foo = new Person({ name: 'Bar', role: null });
assert.strictEqual(foo.role, null);

await Person.create(axl, slash);

const docs = await Person.find({ role: 'guitarist' });

assert.equal(docs.length, 1);
assert.equal(docs[0].name, 'Slash');

默认函数

您也可以将default 模式选项设置为函数。Mongoose 将执行该函数并将返回值用作默认值。

const schema = new Schema({
  title: String,
  date: {
    type: Date,
    // `Date.now()` returns the current unix timestamp as a number
    default: Date.now
  }
});

const BlogPost = db.model('BlogPost', schema);

const post = new BlogPost({ title: '5 Best Arnold Schwarzenegger Movies' });

// The post has a default Date set to now
assert.ok(post.date.getTime() >= Date.now() - 1000);
assert.ok(post.date.getTime() <= Date.now());

setDefaultsOnInsert 选项

当设置了upsert 选项时,Mongoose 也会在update()findOneAndUpdate() 上设置默认值,方法是将您的模式的默认值添加到MongoDB $setOnInsert 操作符。您可以通过将setDefaultsOnInsert 选项设置为false 来禁用此行为。

const schema = new Schema({
  title: String,
  genre: { type: String, default: 'Action' }
});

const Movie = db.model('Movie', schema);

const query = {};
const update = { title: 'The Terminator' };
const options = {
  // Return the document after updates are applied
  new: true,
  // Create a document if one isn't found.
  upsert: true
};

let doc = await Movie.findOneAndUpdate(query, update, options).lean();
doc.genre; // 'Action', Mongoose set a default value.

await Movie.deleteMany({});

doc = await Movie.findOneAndUpdate(query, update, { new: true, upsert: true, setDefaultsOnInsert: false }).lean();
doc.genre; // undefined, Mongoose did not set a default value

您也可以将setDefaultsOnInsert 全局设置为false

mongoose.set('setDefaultsOnInsert', false);

默认函数和this

除非它是在使用setDefaultsOnInsert 的查询上运行,否则默认函数的this 指的是文档。

const schema = new Schema({
  title: String,
  released: Boolean,
  releaseDate: {
    type: Date,
    default: function() {
      if (this.released) {
        return Date.now();
      }
      return null;
    }
  }
});

const Movie = db.model('Movie', schema);

const movie1 = new Movie({ title: 'The Terminator', released: true });

// The post has a default Date set to now
assert.ok(movie1.releaseDate.getTime() >= Date.now() - 1000);
assert.ok(movie1.releaseDate.getTime() <= Date.now());

const movie2 = new Movie({ title: 'The Legend of Conan', released: false });

// Since `released` is false, the default function will return null
assert.strictEqual(movie2.releaseDate, null);