- 英文原版
- 关于中文文档
- 快速上手
- 模式(Schemas)
- 模式类型(SchemaTypes)
- 连接(Connections)
- 模型(Models)
- 文档 (Documents)
- 子文档(Subdocuments)
- 查询 (queries)
- 验证 (validation)
- 中间件 (middleware)
- 填充 (Populate)
- 鉴别器 (Discriminators)
- 插件
- AWS Lambda
- API 文档
- Schema
- Connection
- Document
- Model
- Query
- Aggregate
- SchemaType
- VirtualType
- Error
- Version Compatibility
- FAQ
[
Declaring defaults in your schema ](#declaring-defaults-in-your-schema)
Your schemas can define default values for certain paths. If you create a new document without that path set, the default will kick in.
var schema = new Schema({name: String,role: { type: String, default: 'guitarist' }});var Person = db.model('Person', schema);var axl = new Person({ name: 'Axl Rose', role: 'singer' });assert.equal(axl.role, 'singer');var slash = new Person({ name: 'Slash' });assert.equal(slash.role, 'guitarist');var izzy = new Person({ name: 'Izzy', role: undefined });assert.equal(izzy.role, 'guitarist');Person.create(axl, slash, function(error) {assert.ifError(error);Person.find({ role: 'guitarist' }, function(error, docs) {assert.ifError(error);assert.equal(docs.length, 1);assert.equal(docs[0].name, 'Slash');});});
[
Default functions ](#default-functions)
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
var schema = new Schema({title: String,date: {type: Date,// `Date.now()` returns the current unix timestamp as a numberdefault: Date.now}});var BlogPost = db.model('BlogPost', schema);var post = new BlogPost({title: '5 Best Arnold Schwarzenegger Movies'});// The post has a default Date set to nowassert.ok(post.date.getTime() >= Date.now() - 1000);assert.ok(post.date.getTime() <= Date.now());
[
The setDefaultsOnInsert option
](#the-setdefaultsoninsert-option)
By default, mongoose only applies defaults when you create a new document. It will not set defaults if you use update() and findOneAndUpdate(). However, mongoose 4.x lets you opt-in to this behavior using the setDefaultsOnInsert option.
Important
The setDefaultsOnInsert option relies on the MongoDB $setOnInsert operator. The $setOnInsert operator was introduced in MongoDB 2.4. If you're using MongoDB server < 2.4.0, do not use setDefaultsOnInsert.
var schema = new Schema({title: String,genre: {type: String, default: 'Action'}});var Movie = db.model('Movie', schema);var query = {};var update = {title: 'The Terminator'};var options = {// Return the document after updates are appliednew: true,// Create a document if one isn't found. Required// for `setDefaultsOnInsert`upsert: true,setDefaultsOnInsert: true};Movie.findOneAndUpdate(query, update, options, function (error, doc) {assert.ifError(error);assert.equal(doc.title, 'The Terminator');assert.equal(doc.genre, 'Action');});
[
Default functions and this
](#default-functions-and-this)
Unless it is running on a query with setDefaultsOnInsert, a default function's this refers to the document.
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 nowassert.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 nullassert.strictEqual(movie2.releaseDate, null);
mongoose