Я пытаюсь заполнить документ сразу после его создания в 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
результат запроса, но я надеюсь, что есть более эффективный способ получить результат создания с результатом заполнения.