我一直在用猫鼬的方法。
以下是我的模式:

const GroupSchema = Schema({
  title: String,
  ips: [
    {
    ip: String,
    hostname: String,
    added : { type : Date, default: Date.now }
    }
  ]
});

module.exports = mongoose.model('groups', GroupSchema);

const UserSchema = Schema({
  username: String,
  ip: String,
  groups: [
    {
     _id : { type: Schema.Types.ObjectId, ref: 'groups'},
     added : { type : Date, default: Date.now }
    }
  ]
});

module.exports = mongoose.model('users', UserSchema);

我正试图加入populate()users.groups[]._id但绝对没有运气。
以下是我的尝试:
  User.find().
    populate('groups').
    exec(function (err, user) {
    if (err) return handleError(err);
      console.log(user);
  });

得到这个结果:
 { _id: 5b3e039a2f714d38ccf66cax,
    username: 'rrrr',
    ip: '10.1.1.1',
    groups: [ [Object], [Object] ],
    __v: 0 } ]

我想变成这样:
 { _id: 5b3e039a2f714d38ccf66cax,
    username: 'rrrr',
    ip: '10.1.1.1',
    groups: [{ title: sssss, added: ssss }, {title: xxxx, added: ssss}] ],
    __v: 0 } ]

最佳答案

您可以尝试使用$lookup聚合
如果您使用的是MongoDB 3.4及以下版本

User.aggregate([
  { "$unwind": "$groups" },
  { "$lookup": {
    "from": Groups.collection.name,
    "let": { "groupId": "$groups._id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$_id", "$$groupId" ] } } }
    ],
    "as": "groups._id"
  }},
  { "$unwind": "$groups._id" },
  { "$group": {
    "_id": "$_id",
    "username": { "$first": "$username" },
    "ip": { "$first": "$ip" },
    "groups": { "$push": "$groups" }
  }}
])

如果您使用的是MongoDB 3.6及以上版本
User.aggregate([
  { "$unwind": "$groups" },
  { "$lookup": {
    "from": Groups.collection.name,
    "localField": "groups._id",
    "foreignField": "_id",
    "as": "groups._id"
  }},
  { "$unwind": "$groups._id" },
  { "$group": {
    "_id": "$_id",
    "username": { "$first": "$username" },
    "ip": { "$first": "$ip" },
    "groups": { "$push": "$groups" }
  }}
])

关于node.js - mongoose填充两个简单的模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51217009/

10-12 00:07