第二种吧
2个集合,
红包集合redPacket(_id, rid,money,start,end) => _id,红包id,红包金额,领取开始时间,领取截止时间
红包领取集合userRedPacketRecord(_id,openid,rid,mony,dateline) _id,openid,红包id,红包金额,领取时间
查询的时候lookup连2个表,查一次就行,既可以查询红包是否过期,也能查询某用户是否已领过
// 云函数入口函数
exports.main = async(event, context) => {
const _ = db.command
const $ = _.aggregate
var now = (new Date()).valueOf(), // 当前时间戳,毫秒级
rid = 1, // 红包id
openid = ‘用户openid’
return db.collection(‘redPacket’).aggregate()
.addFields({
isAvailable: $.and([$.gte([’$end’, now]), $.lte([’$start’, now])])
})
.match({
rid: rid
})
.limit(1)
.project({
_id: 0,
rid: 1,
money: 1,
isAvailable: 1,
start:1,
end:1
})
.group({
_id:‘any’,
redPacket: $.push(’$$ROOT’)
})
.lookup({
from: ‘userRedPacketRecord’,
pipeline: $.pipeline()
.match({
rid: rid,
openid: openid
})
.limit(1)
.project({
_id: 0,
rid: 1,
openid: 1,
dateline: 1
})
.done(),
as: ‘userRecord’,
})
.end()
}