使用 mongoose virtuals 有条件地计算条目
Use mongoose virtuals to count entries conditionally
我想在我的 mongoose 模式中添加一个虚拟的。虚拟的目标是计算同一集合中少于引用文档的文档数。因此,例如,我有以下集合:
const mySchema = new mongoose.Schema({
timestamp: {
type: Number
}
})
mySchema.virtual('count', {
ref: 'mySchema',
count: true,
localField: 'timestamp',
foreignField: 'timestamp',
match: function (ref, cmp) {
return ref.timestamp < cmp.timestamp // does not work
}
})
const M = mongoose.model('mySchema', mySchema)
所以当我执行以下操作时:
await M.create({
timestamp: 10
})
await M.create({
timestamp: 20
})
await M.create({
timestamp: 30
})
console.log((await M.find({ timestamp: 30 })).count)
我在控制台中看到“undefined”,但是“count”应该是“2”,因为匹配函数,但是这个函数从来没有被调用过,因为 foreign-/local-field-match(我也不知道知道我是否可以访问匹配函数中的“ref”和“cmp”参数。
当我删除 foreign-/local-field 参数时,它抛出一个错误,因为这些字段似乎是强制性的。我只想添加一个条件,例如“计算时间戳低于当前条目的所有条目”。知道我该怎么做吗?
mySchema.virtual('count').get( async function() {
return await collection.count(.....);
})
除了使用上述方法外,您还需要 mongoose-lean-virtuals 以便在使用 .lean() 时显示计数;
说明:您的方法还需要 mongoose 调用额外的查询。
我想在我的 mongoose 模式中添加一个虚拟的。虚拟的目标是计算同一集合中少于引用文档的文档数。因此,例如,我有以下集合:
const mySchema = new mongoose.Schema({
timestamp: {
type: Number
}
})
mySchema.virtual('count', {
ref: 'mySchema',
count: true,
localField: 'timestamp',
foreignField: 'timestamp',
match: function (ref, cmp) {
return ref.timestamp < cmp.timestamp // does not work
}
})
const M = mongoose.model('mySchema', mySchema)
所以当我执行以下操作时:
await M.create({
timestamp: 10
})
await M.create({
timestamp: 20
})
await M.create({
timestamp: 30
})
console.log((await M.find({ timestamp: 30 })).count)
我在控制台中看到“undefined”,但是“count”应该是“2”,因为匹配函数,但是这个函数从来没有被调用过,因为 foreign-/local-field-match(我也不知道知道我是否可以访问匹配函数中的“ref”和“cmp”参数。 当我删除 foreign-/local-field 参数时,它抛出一个错误,因为这些字段似乎是强制性的。我只想添加一个条件,例如“计算时间戳低于当前条目的所有条目”。知道我该怎么做吗?
mySchema.virtual('count').get( async function() {
return await collection.count(.....);
})
除了使用上述方法外,您还需要 mongoose-lean-virtuals 以便在使用 .lean() 时显示计数;
说明:您的方法还需要 mongoose 调用额外的查询。