Javascript 如何引用mongoose中另一个模型的字段
我试图根据用户名链接卡片模式中用户模型的一些字段。 例如,这是我的卡片模式Javascript 如何引用mongoose中另一个模型的字段,javascript,mongodb,express,mongoose,Javascript,Mongodb,Express,Mongoose,我试图根据用户名链接卡片模式中用户模型的一些字段。 例如,这是我的卡片模式 const CardSchema = new mongoose.Schema({ text: { type: String, }, username: { type: String, ref: 'User', required: true }, userSticker: { This is
const CardSchema = new mongoose.Schema({
text: {
type: String,
},
username: {
type: String,
ref: 'User',
required: true
},
userSticker: {
This is what I need to get from the user model based on the username or user id
}
这就是用户模型的样子:
const UserSchema = new mongoose.Schema({
username: {
type: String,
},
userSticker: {
type: String,
}
我需要的是在卡片模式中始终具有与具有该用户名的用户相同的用户标签。在创建卡片时添加它将不起作用,因为用户标签可能会更改,我希望在发生这种情况时卡片模式中的字段也会更改,所以我想它应该类似于一个引用。更新:好的,我已经读到mongoose为您做了这件事。它可以对表进行关系建模,并根据模式中定义的ref填充关系数据 看看这个 本节针对MongoDB
这里有两种解决方案,因为MongoDB不像SQL那样是关系数据库 第一种解决方案是在字段值更改时复制数据并更新所有字段
const CardSchema = new mongoose.Schema({
text: {
type: String,
},
username: {
type: String,
},
userSticker: {
type: String,
}
})
const UserSchema = new mongoose.Schema({
username: {
type: String,
},
userSticker: {
type: String,
}
})
然后,每当用户标签更改时,您需要查询卡片收集并更新与用户名匹配的所有用户标签
第二种解决方案是在集合之间手动创建引用
const CardSchema = new mongoose.Schema({
text: {
type: String,
},
user_id: {
type: String
}
})
const UserSchema = new mongoose.Schema({
_id: {
type: String,
},
username: {
type: String,
},
userSticker: {
type: String,
}
})
然后,当您查询文档卡集合时,您可以对用户\u id引用的文档执行第二次查询
- 第一个写速度较慢,但读速度较快
- 第二种方法写得快,读得慢(对查询进行分页)
MongoDB不是关系数据库。您需要同时更改这两个字段或使用SQL。同时更改这两个字段?我知道这很糟糕,但当您更改用户集合中的userSticker时,您必须更新卡集合中与用户匹配的所有userSticker。作为替代方法,您也可以手动引用您的集合,但这需要多次获取。我将发布一个答案,尽我所能解释两种解决方案。
const cardSchema = new mongoose.Schema({
text: {
type: String,
},
username: {
type: String,
ref: 'User',
required: true
},
userSticker: {
type: Schema.Types.ObjectId,
ref: 'User'
}
};
const userSchema = new mongoose.Schema({
username: {
type: String,
},
userSticker: {
type: String,
}
}
const User = mongoose.model('User', userSchema);
const Card = mongoose.model('Card', cardSchema);
Card.findbyId(id).populate('userSticker', 'userSticker').exec(function(err, card) {/* Do stuff... */})