mongo 插入多维数组 唯一 $ne+$push

mongo $addToSet 用于处理普通数组不重复的问题
但是遇到 多维的就会出现问题
?
故只能通过$ne+$push的方式来解决
?
代码如下(egg2.x mongoose5.x)

Schema
const AllPsListSchema = new Schema({
// 分类中文名称
psName: {
type: String,
required: [true, '服务名称不能为空'],
unique: true,
},
// 分类英文名称
psEnName: {
type: String,
},
// 服务状态 [0/停用,1/正常,2/维护,3/下线]
psState: {
type: Number,
default: 1
},
// 服务子类
psChild: [{
// 产品/服务名称
name: {
type: String,
required: [true, '服务/产品名称不能为空'],
unique: true
},
// 产品/服务英文名称
enName: {
type: String,
required: [true, '服务/产品英文名称不能为空'],
unique: true
},
// 服务状态 [0/停用,1/正常,2/维护,3/下线]
state: {
type: Number,
default: 1
},
// [0/删除,1/锁定,2/正常] 1/锁定意思为不可删除,系统保留
status: {
type: Number,
default: 2
}
}],
// [0:删除,1:锁定,2:正常] 1/锁定意思为不可删除,系统保留
status: {
type: Number,
default: 2
}
}, {
timestamps: {
createdAt: 'created',
updatedAt: 'updated'
}
})

statics
?
        creatPSChild: async function (_id, bodys) {
const result = await this.findOneAndUpdate({ _id, 'psChild.name': { $ne: bodys.name }, 'psChild.enName': { $ne: bodys.enName } }, {
$push: {
'psChild': bodys
}
});
return { data: result }
}

0 个评论

要回复文章请先登录注册