Populate()指定多个模型

时间:2018-06-12 21:15:41

标签: node.js mongodb mongoose

我希望在populate()请求中生成find()但是指定多个模型,因此如果在第一个指定的模型上没有找到,则在第二个上进行填充。< / p>

以下是我想要做的一个示例:

const userSch = new Schema({
    username: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
    mail: {
      type: String,
      required: true,
      unique: true,
    }
});

const botSch = new Schema({
    username: {
      type: String,
      required: true,
    },
    token: {
      type: String,
      required: true,
      unique: true,
    },
    owner: mongoose.Schema.Types.ObjectId
 });

const nspSch = new Schema({
  name: String,
  channels: [channels],
  users: [{
    id: {
      type: mongoose.Schema.Types.ObjectId,
    },
    bot: {
      type: Boolean,
    }
  }],
});

const channels = new Schema({
    name: String,
    message: [{
        user: {
          type: Schema.Types.ObjectId,
        },
        content: String,
    }],
});

const nsp = mongoose.model('namespace', nspSch);
const Auth = mongoose.model('users', userSch);
const BotAuth = mongoose.model('bots', botSch);

function returnMs(nspID, channelID, callback) {
  nsp.findOne({'_id': nspID}).populate({
    path: 'channels.message.user',
    model: 'users' || 'bots',
    select: '_id username',
  })
  .exec(function(err, r) {
    ...
  })
}

如果有npm个软件包或解决方案甚至是跟踪代码,请分享。

谢谢

0 个答案:

没有答案