创建后如何在其他模式中保存模式的ID

时间:2019-03-26 15:00:31

标签: javascript mongoose schema

我正在尝试创建书籍和作者的简单CRUD。创建图书时,我想将图书的ID保存在作者模式中,但是当我尝试在数据库上没有任何反应时。

这是我的控制器代码

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);

0 个答案:

没有答案