如何在未设置 ObjectId
字段的情况下搜索执行 .findOne
的文档?我找不到是否应该搜索 null
或 undefined
或其他内容。
在下面的示例中,我试图找到一个文档,其中“email”值已知但尚未设置 userId:
var joinRequest = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true, trim: true },
code: { type: String, uppercase: true, trim: true, select: false },
lastSent: { type: Date },
userId: { type: mongoose.Schema.Types.ObjectId, select: false }
});
然后,ObjectId
字段可以为空吗?我应该在这里使用 String
吗?
最佳答案
在 MongoDB 上下文中关于 undefined
的一些事情
不存储值为 undefined
的属性。所以以下将没有 a
属性
db.insert({a : undefined})
但是对于数组,undefined
值被转换为 null
db.insert({a : [undefined]}) //stores {a : [null]}
undefined
用作条件时也有奇怪的行为
db.users.find({a : undefined}) //finds everything
db.users.findOne({a : undefined}) //always returns the first document (which is a problem for you)
db.users.update({a : undefined}, {a : true}) //only updates documents with no a property
所以我会避免使用 undefined
并且可能假装它根本不存在。请改用 null
,因为它已存储并且有时不会作为条件删除。
比如
db.users.insert({email : "email@domain.com", userID : null});
db.users.findOne({email : "email@domain.com", userID : null});
如果你决定使用 undefined,尽管这样做
db.users.insert({email : "email@domain.com"});
db.users.findOne({email : "email@domain.com", userID : { exists : false }}); //works for null as well
http://docs.mongodb.org/manual/reference/operator/query/exists/
关于mongoose - 对象 ID 为空的 Mongoose 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27513844/