如何真正设置猫鼬默认值,特别是.布尔值? [英] How to really set a Mongoose default, esp. Boolean?

查看:68
本文介绍了如何真正设置猫鼬默认值,特别是.布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下架构:

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

但是,我发现如果查询日期",则日期是在文档上设置的,但是如果查询只读",则日期不会设置为false,但在文档上将返回false.例如:

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({})

我将收到所有文档,并且属性"readonly"将列为"false".

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();

上面相同的find命令将列出此文档.似乎布尔值的默认设置是隐式设置的,并且在读取文档而不查询时可用.有没有一种方法可以确保在所有文档上都可以设置它并且可以像创建"日期属性一样找到它,还是必须在所有新文档上手动设置它?

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?

推荐答案

代替

readonly: {
    type: Boolean,
    default: false
}

尝试将''设置为false,这样将是:

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

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

根据猫鼬文档,猫鼬将以下值转换为false:

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

  • 假"
  • 0
  • '0'
  • 'no'

这篇关于如何真正设置猫鼬默认值,特别是.布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆