在 其他用户个人资料上时,如何为猫鼬模式建模以获取这三个按钮?
我的用户架构
My users schema
const schema = new Mongoose.Schema({ firstName: { type: String, default: '', trim: true }, lastName: { type: String, default: '', trim: true }, }, { timestamps: true })
我无法为此找到正确的建模…并且还建议 在建模之后建议汇总…
所以最后我做到了,我认为这可能是用 mongodb和mongoose 做到的最佳方法
1.为用户创建一个模型。
var Schema = mongoose.Schema const usersSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, friends: [{ type: Schema.Types.ObjectId, ref: 'Friends'}] }, {timestamps: true}) module.exports = mongoose.model('Users', usersSchema)
2.为有枚举被接受,拒绝,未决和请求的朋友创建模型。
const friendsSchema = new Schema({ requester: { type: Schema.Types.ObjectId, ref: 'Users'}, recipient: { type: Schema.Types.ObjectId, ref: 'Users'}, status: { type: Number, enums: [ 0, //'add friend', 1, //'requested', 2, //'pending', 3, //'friends' ] } }, {timestamps: true}) module.exports = mongoose.model('Friends', friendsSchema)
3.现在api调用–>假设我们有两个用户UserA和UserB…因此, 当UserA当时要求UserB成为朋友时,我们制作了两个 文档,以便UserA可以看到请求的内容,而UserB可以看到待处理的内容, 同时我们在用户的朋友中推送这些文档的_id
const docA = await Friend.findOneAndUpdate( { requester: UserA, recipient: UserB }, { $set: { status: 1 }}, { upsert: true, new: true } ) const docB = await Friend.findOneAndUpdate( { recipient: UserA, requester: UserB }, { $set: { status: 2 }}, { upsert: true, new: true } ) const updateUserA = await User.findOneAndUpdate( { _id: UserA }, { $push: { friends: docA._id }} ) const updateUserB = await User.findOneAndUpdate( { _id: UserB }, { $push: { friends: docB._id }} )
4.如果用户B接受请求
Friend.findOneAndUpdate( { requester: UserA, recipient: UserB }, { $set: { status: 3 }} ) Friend.findOneAndUpdate( { recipient: UserA requester: UserB }, { $set: { status: 3 }} )
5.如果用户B拒绝请求
const docA = await Friend.findOneAndRemove( { requester: UserA, recipient: UserB } ) const docB = await Friend.findOneAndRemove( { recipient: UserA, requester: UserB } ) const updateUserA = await User.findOneAndUpdate( { _id: UserA }, { $pull: { friends: docA._id }} ) const updateUserB = await User.findOneAndUpdate( { _id: UserB }, { $pull: { friends: docB._id }} )
6.获取所有的朋友,并检查是否登录用户的朋友该用户或不
User.aggregate([ { "$lookup": { "from": Friend.collection.name, "let": { "friends": "$friends" }, "pipeline": [ { "$match": { "recipient": mongoose.Types.ObjectId("5afaab572c4ec049aeb0bcba"), "$expr": { "$in": [ "$_id", "$$friends" ] } }}, { "$project": { "status": 1 } } ], "as": "friends" }}, { "$addFields": { "friendsStatus": { "$ifNull": [ { "$min": "$friends.status" }, 0 ] } }} ])