How to really set a Mongoose default, esp. Boolean?

半城伤御伤魂 提交于 2019-12-25 00:55:03

问题


I have the following schema:

const profileSchema = new Schema({
created: {
    type: Date,
    default: Date.now
    },
readonly: {
    type: Boolean,
    default: false
    }
});
const Profile = mongoose.model('profile',profileSchema);

However I have found that if I query for "date", the date is set on documents, but if I query for "readonly" it is NOT set to false, but will return false on the document. For example:

Profile.find({readonly: false})

Will return no documents. However, if I do:

Profile.find({})

I will receive all the documents and the property "readonly" will be listed as "false".

At the same time if when I create the document I do:

var newProfile = { readonly: false };
new Profile(newProfile).save();

The same find command above will list this document. It seems that the default for booleans is implicitly set and is available when the document is read, not queried. Is there a way to make sure it is set and findable on all documents just as the "created" date property is, or do I have to set it on all new documents manually?


回答1:


Instead of

readonly: {
    type: Boolean,
    default: false
}

Try putting ' ' to false, so it will be:

readonly: {
    type: Boolean,
    default: 'false'
}

According to mongoose documentation, mongoose casts the following values to false:

  • 'false'
  • 0
  • '0'
  • 'no'


来源:https://stackoverflow.com/questions/53188592/how-to-really-set-a-mongoose-default-esp-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!