gpt4 book ai didi

node.js - 如何在 Mongoose 中引用引用来访问子文档?

转载 作者:太空宇宙 更新时间:2023-11-04 00:13:10 25 4
gpt4 key购买 nike

我想使用 Mongoose 访问子文档

这是我的对话架构:

const Conversations = new mongoose.Schema({

userOneId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
userTwoId: {
type: Schema.Types.ObjectId,
ref: 'User'
}

这是我的用户模型架构:

....
conversations: [{ type: Schema.Types.ObjectId, ref: 'Conversations' }]
});

插入后我得到这个:

{
"_id": {
"$oid": "5a6fa114ffc53523705d52af"
},
"created_at": {
"$date": "2018-01-29T22:32:52.930Z"
},
"messages": [],
"__v": 0
}

我插入了这个:

 "conversations": [
{
"$oid": "5a6fa14a5562572a541bacae"
},

我把这个:

  Object.assign(conversation, {userOneId: user._id});
Object.assign(conversation, {userTwoId: friend._id});

我想访问 "$oid": "5a6fa114ffc53523705d52af" 以获取 userOneIduserTwoId 信息。

最佳答案

您需要使用populate .

基本上,在用户对象的“对话”属性中,您只有对话的 ObjectId,而不是整个 mongoose 对象。当您在数据库中查询一个或多个用户时,您必须告诉 mongoose 您希望它用整个对象替换 ObjectId。

//lets say you have a variable, userId, inside of which you have the id
//of a user, and now you're querying the database for that user

User.findById(userId).populate("conversations")
.exec(function(err, foundUser){
if(err){
console.log(err):
} else {
console.log(foundUser.conversations);
}
});

如果您要使用实际的用户 _id 运行上面的代码,那么(除非出现错误)您将在控制台中打印而不是对话 Mongoose ID 数组、对话 Mongoose 对象数组。整个事情。

如果您只希望对话有两个属性,userOneId 和 userTwoId,则将 populate 与 select 结合起来。而不是

.populate("conversations")

使用

.populate({
path: "conversations",
select: "userOneId userTwoId"
})

关于node.js - 如何在 Mongoose 中引用引用来访问子文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com