【问题标题】:how to populate two collection on a same record in mongoose and node js如何在猫鼬和节点js中的同一记录上填充两个集合
【发布时间】:2015-06-10 15:21:28
【问题描述】:

我是猫鼬和节点 js 的新手。我在我的项目中遇到了一些麻烦。 这是我的用户模型

UserSchema = new Schema({
account:String,
password:String,
display_name:String )}

和朋友模型

FriendSchema = new Schema({

friend_from_id:{
    type:Schema.ObjectId,
    ref:'users'
},
friend_to_id:{
    type:Schema.ObjectId,
    ref:'users'
}});

和 user_status 模型

UserStatusSchema = new Schema({

user_id:{
    type:Schema.ObjectId,
    ref:'users'
},
status:{
    type:Boolean
},
status_text:String,
last_updated_at:String});

如何填充或以任何方式从这样的朋友模型中生成结果

{
"_id": "55145b6b8b9c9e6c1f739441",
"friend_to_id": {
    "_id": "5502976dbef9fa180d28ea21",
    "display_name": "Jason",
    "account": "xxx@ginmed.com",
    "status":false,
    "status::"how it's going"
},
"friend_from_id": {
    "_id": "5502976dbef9fa180d28ea21",
    "display_name": "SonPham",
    "account": "yyy@ginmed.com",
    "status":true,
    "status::"how to do it"}

这意味着我想将 user_status 和 user 模型结合在一个朋友模型字段中

【问题讨论】:

    标签: node.js mongodb validation mongoose mongoose-populate


    【解决方案1】:

    我不太确定我是否理解这个问题,但您似乎有一个用户列表,您希望为这些用户建立一个自我引用的多对多关系(即用户可以有朋友并成为许多其他用户的朋友)。要启用此功能,您需要更新用户对象(可能带有其他信息)和朋友集合(带有添加/删除的关系)。在不对解决方案发表评论的情况下,我认为您会通过查看 mongoose 的“钩子”中间件 (http://mongoosejs.com/docs/middleware.html) 找到所需的内容。这允许您在保存前和保存后阶段执行附加功能。保存用户模型后,您可以使用 post save hook 更新好友模型。

    UserSchema.post('save', function(doc) {
        // Remove deleted friendships and add new ones here
    });
    

    至于您提出的解决方案,我会查看 many to many relationship with nosql (mongodb and mongoose) 以获得一些可能的替代方案/改进。

    【讨论】:

    • 不客气。如果您觉得有用,请提高评分。谢谢!
    【解决方案2】:

    您可以使用以下查询来填充这两个集合

    FriendSchema.findOne({}).
    populate(friend_from_id).
    populate(friend_to_id).
    exec(function (err, schema) {});
    

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 2015-11-19
      • 2018-10-14
      • 2020-01-20
      • 2021-08-04
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      相关资源
      最近更新 更多