Как сохранить идентификатор схемы в другой схеме при ее создании - PullRequest
0 голосов
/ 26 марта 2019

Я пытаюсь создать простой CRUD из книг и авторов. Я хочу сохранить идентификатор книги в схеме автора при создании книги, но при попытке ничего не происходит в базе данных.

Это мой код контроллера

exports.post = async (req, res, next) => {
  try {
    await repository.post(req.body).then(() => {
      helper.updateBooks(req.body.author);
    });
    res.status(201).send({ message: 'Livro criado com sucesso' });
  } catch (error) {
    res.status(500).send({
      message: 'Falha ao processar requisição',
      data: error
    });
  }
};

сообщение репозитория вызывает эту функцию ниже

exports.post = async (data) => {
  let book = new Book(data);
  await book.save();
}

и .then () в первом методе вызывает функцию ниже

exports.updateBooks = async (author_id) => {
  console.log(author_id);
  Author.findOneAndUpdate(author_id, {
    $push: {
      books: author_id
    }
  })
};

Редактировать

Вот схема автора

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const AuthorSchema = new Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  books: {
    type: [mongoose.Schema.Types.ObjectId],
    ref: 'Book'
  },
  slug: {
    type: String,
    required: true,
    trim: true,
    index: true,
    unique: true
  },
  birth_date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Author', AuthorSchema);

А вот и модель книги

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BookSchema = new Schema({
  title: {
    type: String,
    required: true,
    trim: true
  },
  slug: {
    type: String,
    required: true,
    trim: true,
    index: true,
    unique: true
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Author',
    required: true
  },
  description: {
    type: String,
    trim: true
  },
  num_of_pages: {
    type: Number,
  },
  publisher: {
    type: String,
    trim: true
  },
  published_date: {
    type: Date,
    default: Date.now
  },
  tags: [{
    type: String,
    required: true
  }]
});

module.exports = mongoose.model('Book', BookSchema);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...