当mongoDb中另一个模型字段发生变化时,我如何更新模型字段?



我试图使postSchema用户名得到更新每当userSchema用户名改变

//This is the PostSchema
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: false,
},
profileDp: {
type: String,
required: true,
},
})
//This is the user Schema
const UserSchema = new mongoose.Schema(
{
_id: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: false,
},
profilePic: {
type: String,
required: true,
},

那么我如何在postSchema中创建一个关系,这样每当userSchema用户名改变时,postSchema用户名也应该改变?

到目前为止,我已经看到$set, ref甚至populate()被推荐,但我仍然不确定如何做到这一点。

您可以在UserSchema上添加pre-hooks,同时像下面这样更新用户名。

UserSchema.pre(["updateOne", "findOneAndUpdate", "findByIdAndUpdate", "updateMany" ], async function (next) {
if(this.get("username")){
let userDoc = await mongoose.model("user").findOne(this._conditions);
await mongoose.model("post").updateOne({ username: userDoc.username },{
username: this.get("username")
});
}
next();
}))

检查上面的例子,每当你的用户名更新,它将自动更新后的文档有关pre-hooks的更多信息,请访问此链接https://mongoosejs.com/docs/middleware.html

最新更新