gpt4 book ai didi

node.js - Mongoose 具有 true 的独特 bool 值

转载 作者:太空宇宙 更新时间:2023-11-03 22:53:02 25 4
gpt4 key购买 nike

我知道如何在我的架构中设置一个唯一的字符串,如下所示:

string: { type: String, unique: true }

但是有没有一种方法可以在对象上拥有具有 true 值的唯一 bool 值并使用 false (默认设置)?我需要的是:如果我尝试保存一个具有 true 值的对象,并且一个具有 true 值的对象已经存在,则会返回错误。

感谢您的帮助。

最佳答案

您可以使用 MongoDB 对 partial indexes 的支持来完成此操作这是在 3.2 中添加的。

var mySchema = new Schema({ oneTrue: Boolean });
mySchema.index({oneTrue: 1}, {unique: true, partialFilterExpression: {oneTrue: true}});

这将仅在值为 trueoneTrue 字段上创建唯一索引。这样,就允许多个具有 false 值的文档,但只有一个值为 true 的文档。

关于node.js - Mongoose 具有 true 的独特 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35407959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com