我正在使用类似于以下的猫鼬模式:
const actionSchema = {
actions: {
type: [{
actionName: {
type: String,
required: true
},
count: {
type: Number,
default: 0,
required: true
},
users: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
}]
}};
它是发布架构的嵌套架构。 这里,动作是动态生成的,并且通过计数维护该动作的人数,并且通过用户数组维护其身份。
如您所见,动作是对象的数组,进一步包含用户数组。 我想检查提供的用户ID是否存在于任何操作对象中,然后将其从数组中删除并减少计数。
对mongoose和mongodb完全陌生,我看到的一种简单方法是使用Post.findById()
查找帖子,该帖子必须进行更新,运行js循环,更新帖子并调用.save()
。但是,当用户数组具有数千个用户ID时,这可能会非常昂贵。
我尝试过.update()
,但在这种情况下不知道如何使用它。
如何向Post Model中添加方法(如postSchema.methods.removeUserAction
)?这样可以访问this
中的文档,并可以更新文档并因此调用.save()
。是否会将完整文档加载到客户端节点应用程序?
所以请提出正确的建议。 谢谢。
答案 0 :(得分:1)
例如,您应该简化模型
// Model - Actions Model
const actionSchema = {
actionName: {
type: String,
required: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
};
您可以轻松地通过Model.count()
获取全部操作,使用Model.count({ actionName: 'action name'})
获取特定操作计数,并使用Model.delete(condition)
删除条目。除非有理由对它进行这种建模。