乐闻世界logo
搜索文章和话题

How to default an embedded document to null with mongoose

1个答案

1

In Mongoose, when defining a model's schema, you can specify default values for each field. If you want a field's default value to be null, you can use the default keyword when defining the field and set it to null.

Here is an example of how to set a field's default to null:

javascript
const mongoose = require('mongoose'); const schema = new mongoose.Schema({ name: String, age: Number, phone: { type: String, default: null // Set the default value of the phone field to null } }); const User = mongoose.model('User', schema); // When creating a new User object without providing a value for the phone field, it will default to null. const user = new User({ name: 'John Doe', age: 30 }); console.log(user.phone); // Output: null

In this example, even if you don't specify a value for the phone field, its default value will be null. When saving to the database, if the phone field is not assigned a value, it will be stored as null.

This approach is typically used when you need to distinguish between a field not being assigned a value and a field being assigned an empty value. By setting the default value to null, you explicitly indicate that the field exists but has not been populated with any value.

2024年6月29日 12:07 回复

你的答案