使用Mongoose在子文档不存在的地方返回Mongo文档?
帮帮我! 我正在失去理智 我只需要返回一个Mongo document
,使用Mongoose
, IF
子文档不存在。
我的模式:
var userSchema = new mongoose.Schema({ email: {type: String, unique: true, lowercase: true}, password: {type: String, select: false}, displayName: String, picture: String, facebook: String, deactivation: deactiveSchema }); var deactiveSchema = new mongoose.Schema({ when : { type: Date, default: Date.now, required: true }, who : { type: Schema.Types.ObjectId, required: true, ref: 'User' } });
我的目标是通过他们的facebook
ID查找用户,如果他们还没有被停用。
如果它们已被停用,则将存在deactivation
子文档。 当然,为了节省空间,如果它们处于活动状态, 则不存在deactivation
。
另外一个方面,我也担心如何正确构build这个逻辑的索引。
我会张贴片段,但每一个尝试都是错误的。 =(
你可以使用$exists
操作符:
userSchema.find({deactivation:{$exists:false}}).exec(function(err,document){ });
或$ne
:
userSchema.find({deactivation:{$ne:null}}).exec(function(err,document){ });
既然你是退休的数据,而不是删除,我会采取两种方法之一:
退役的国旗 (推荐)
添加到您的模式:
retired: { type: Boolean, required: true }
并为此查询添加一个索引:
userSchema.index({facebook: 1, retired: 1})
并查询:
User.find({facebook: facebookId, retired: false}, callback)
查询是否存在
User.find().exists("deactivation", false).exec(callback)
后者会慢一些,但是如果你真的不想改变什么的话,它就会起作用。 我build议花一些时间阅读mongo文档的索引部分。
Mongoose有很多选项来定义查询的条件和一些样式来编写查询:
条件对象
var id = "somefacebookid"; var condition = { facebook : id, deactivation: { $exists : true} }; user.findOne(condition, function (e, doc) { // if not e, do something with doc })
http://mongoosejs.com/docs/queries.html
查询生成器
或者,如果您正在寻找更接近于SQL的东西,则可能需要使用查询生成器语法。 例如:
var id = "somefacebookid"; users .find({ facebook : id }). .where('deactivation').exists(false) .limit(1) .exec(callback);