Question about Mongoose models with express

I love how mongoose organizes models but I’m still wondering what the best approach is to storying the action database queries. Normally in an MVC architecture you put those in models but it looks like mongoose models just store the scheme and you then call queries in your controller files. Is this correct? Or did I miss something. Doesn’t seem like the correct place to do that.

I tried using mongoose ‘static’ functions but couldn’t get those to work.

Would I be right in thinking that your models are structured something along these lines?

const mongoose = require('mongoose');
const shortid  = require('shortid');

const bookSchema = mongoose.Schema({
  shortId: { type: String, trim: true, unique: true, default: () =>  shortid.generate(), required: true },
  title: { type: String, trim: true, required: true },
  author: { type: String, trim: true },
  image: { type: String, trim: true },
  description: { type: String, trim: true },
  googleId: { type: String, trim: true },
  index: { type: Number },
  user: { type: mongoose.Schema.ObjectId, ref: 'User' },
  entries: [{
    name: { type: String, trim: true, default: 'anonymous' },
    message: { type: String, trim: true },
    location: { type: String, trim: true },
    lat: { type: Number, trim: true },
    lng: { type: Number, trim: true },
    date: { type: Date }
  }, {
    timestamps: true
  }]
}, {
  timestamps: true
});

bookSchema.pre('save', function(done) {
  return this.model('User').findByIdAndUpdate(this.user, { $addToSet: { books: this._id }}, done);
});

module.exports = mongoose.model('Book', bookSchema);

And your controllers like this?

module.exports = {
  index: booksIndex,
  create: booksCreate,
  show: BooksRegister,
  update: booksUpdate,
  delete: booksDelete
};

const Book = require('../models/book');

function booksIndex(req, res) {
  Book.find({})
  .populate('user')
  .exec((err, books) => {
    if(err) return res.status(500).json({ message: 'Something went wrong.' });
    return res.status(200).json(books);
  });
}

function booksCreate(req, res) {
  const book = new Book(req.body);
  book.save((err, book) => {
    if (err) return res.status(500).json({ message: 'Something went wrong.' });
    return res.status(201).json(book);
  });
}

function BooksRegister(req, res){
  Book
  .findOne({
    shortId: req.params.shortId
  }, (err, book) => {
    if (err) return res.status(500).json({ message: 'Something went wrong.' });
    if(!book) return res.status(404).json({ message: 'Book not found' });
    return res.status(200).json(book);
  });
}

function booksUpdate(req, res){
  Book
  .findOneAndUpdate({
    shortId: req.params.shortId
  }, req.body, { new: true }, (err, book) => {
    if (err) return res.status(500).json({ message: 'Something went wrong.' });
    if (!book) return res.status(404).json({ message: 'Book not found' });
    return res.status(200).json(book);
  });
}

function booksDelete(req, res){
  Book.findOneAndRemove({
    shortId: req.params.shortId
  }, err => {
    if (err) return res.status(500).json({ message: 'Something went wrong.' });
    return res.sendStatus(204);
  });
}

That is correct.

That was the way I learnt how to use them, and have used that particular pattern on a number of occasions. That’s not to say it’s the only way, but it does seem to be an established way of doing things.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.