在创建模型后立即使用Mongoose填充

时间:2018-10-22 01:58:41

标签: database mongodb mongoose mongoose-populate

在Mongoose中创建文档后,我正尝试填充该文档。

我查看了堆栈溢出,但是发现的所有内容都与.find相关,而我已在其他查询上成功实现了此

这是我的模特:

import { mongoose, Schema } from '../utils';

const playedGameSchema = new Schema ({
  created: Date,
  updated: Date,
  game: {
    type: Schema.Types.ObjectId,
    ref: 'game'
  },
  creator: {
    id: {
      type: Schema.Types.ObjectId,
      ref: 'user'
    },
    score: Number
  },
  partners: [{
    id: {
      type: Schema.Types.ObjectId,
      ref: 'user'
    },
    score: Number
  }]
});
module.exports = mongoose.model('PlayedGame', playedGameSchema);

还有我的创建算法:

  connectToDatabase().then(() => {
    PlayedGame.create(game)
      .then(game => {
        console.log('before', game)
        game.populate({ path: 'game', select: 'name', model: Game })
            .populate({ path: 'creator.id', select: 'preferred_username', model: User })
            .populate({ path: 'partners.id', select: 'preferred_username', model: User })
            .then(result => console.log(result));

        console.log('after', game)

        cb(null, {
          statusCode: 200,
          headers: defaultResponseHeader,
          body: JSON.stringify(game)
        })
      })
      .catch(err => cb(null, {
        statusCode: err.statusCode || 500,
        headers: { 'Content-Type': 'text/plain' },
        body: err
      }));
  });

我可能会在创建之后立即执行find,然后执行populate查询结果,但是我希望有一种更有效的方法来接收带有填充结果的创建结果。

0 个答案:

没有答案