【问题标题】:mongoose populate naming and structure猫鼬填充命名和结构
【发布时间】:2016-10-25 07:52:29
【问题描述】:

我有这个“用户”模型来存储朋友,这个朋友有一些选择

// Prepare schema
var schema = new db.Schema({
    friends: [{
        active : Boolean,
        user : { type: db.Schema.ObjectId, ref: 'user' },
        options : [{ type: db.Schema.ObjectId, ref: 'friend_option' }],
    }],
    image: { type: db.Schema.ObjectId, ref: 'file' },
    password: { 
        type: String, 
        select: false
    },
    email: String,
    name: String,
    udid: [{
        device: String,
        udid: String
    }],
    created_on: Date
});

这里有一位用户和他的朋友

var friendQuery = User.find( {_id:req.params.id});
friendQuery.select('friends');
friendQuery.populate({ path: 'friends._id', model: 'user', select:'_id name' });        
friendQuery.exec(
    function(err, user) {
    if (err)
        res.send(err);
        res.send(user);
});

我的问题是,为什么结果的名称与我的模型不同?为什么friends->_id->_id 改为friends->user->_id?

friends": [
      {
        "_id": {
          "_id": "58025664c154929d3207b232",
          "name": "User 1"
        },
        "options": [
        ],
        "active": false
      },
      {
        "_id": {
          "_id": "580257e1e3cd4fc7326fa97b",
          "name": "User 2"
        },
        "options": [
        ],
        "active": false
      }
    ]

另一种选择,此解决方案适用于假设的大型应用程序吗?

【问题讨论】:

    标签: node.js mongodb mongoose populate


    【解决方案1】:

    您使用此方法的方式不正确,只需在查询中进行简单更改

     var friendQuery = User.find( {_id:req.params.id});
    friendQuery.select('friends');
    friendQuery.populate({ path: 'friends.user', model: 'user', select:'_id name' });        
    friendQuery.exec(
        function(err, user) {
        if (err)
            res.send(err);
            res.send(user);
    });
    

    当您在朋友数组中引用您的用户时,只需将查询中的 _id 替换为绝对适合您的用户

    【讨论】:

      猜你喜欢
      • 2015-07-13
      • 2016-10-10
      • 2019-09-16
      • 2015-08-26
      • 2015-07-13
      • 2020-01-17
      • 2021-05-03
      • 2021-01-09
      相关资源
      最近更新 更多