Javascript 使用mongoose不';t返回目标引用集合
我有两个集合,一个是信用,另一个是用户 信用 用户 正如您所看到的,信用证的用户id与用户的_id相同。在检索该用户时,如何检索信用证文档?我尝试了模式中的ref,但没有得到信用数据,就像这样Javascript 使用mongoose不';t返回目标引用集合,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有两个集合,一个是信用,另一个是用户 信用 用户 正如您所看到的,信用证的用户id与用户的_id相同。在检索该用户时,如何检索信用证文档?我尝试了模式中的ref,但没有得到信用数据,就像这样 exports.getUser = async function(req, res) { const user = await User.findOne({_id: req.query.id}) .populate('credit') .exec() res.json(user)
exports.getUser = async function(req, res) {
const user = await User.findOne({_id: req.query.id})
.populate('credit')
.exec()
res.json(user)
}
CreditSchema
const CreditSchema = new Schema({
userId: Schema.Types.ObjectId,
credit: {
type: Number,
default: 0
},
log: [String]
})
const UserSchema = new Schema({
fullName: {
type: String
},
// etc.....
credit: {
type: Schema.Types.ObjectId,
ref: 'Credit'
}
})
UserSchema
const CreditSchema = new Schema({
userId: Schema.Types.ObjectId,
credit: {
type: Number,
default: 0
},
log: [String]
})
const UserSchema = new Schema({
fullName: {
type: String
},
// etc.....
credit: {
type: Schema.Types.ObjectId,
ref: 'Credit'
}
})
在您为“用户”集合显示的文档中,我没有看到
“信用”
。同时切换到JSON视图,只需复制并粘贴“文本”而不是屏幕截图。较低级别的代表帐户无法发布“图片”是有原因的,这一小段时间就是为了给你上一课。我想我知道问题出在哪里,当我使用findOneAndUpdate为credit更新true时,我没有更新我的用户文档,因此信用缺失。如果你有“很多”缺失,那么你实际上可以设置一个使用现代版本的mongoose“virtual”,并使其引用已经出现的外来值。此外,$lookup
操作符确实是实现这一点的现代方法。All.populate()
的作用是执行另一个查询来检索结果,其中as$lookup
允许在单个请求中执行此操作。无论如何,您确实不“需要”两个集合中的引用,并且确实应该选择“一个方向”并保持它,以避免混淆更新模式。就像您已经做的那样。