2021年1月2日星期六

In Node.js and Mongoose, how can I use a variable in place of a model name?

I have a couple of collections with tons of documents, like "all books in the world" and "all movies in the world." To reduce the size of my collections and because there are so many unique properties between the two, I have them as separate collections.

But I have a lot of Node.js functions where the only difference between two functions is the model I am querying on. I would like to make more generic functions to reduce the amount of code.

To greatly simplify the example, I currently have this:

import { Book, Movie } from '../models'    const getBooks = (bookId) => Book.findById(bookId)  const getMovies = (movieId) => Movie.findById(movieId)  

And I would like to be able to do something like this, where type would be either 'Book' or 'Movie':

import { Book, Movie } from '../models'  const getItems = (type, itemId) => type.findById(itemId)  

I have tried all kinds of things, but the only thing I can get to work is having ternary operators all over the place (which will probably become switch statements when I add additional collections).

Is there a more elegant way of doing this? And if so, recommended? Or does this just point to schema design issues?

This would kind of be like using computed properties, but not for the name of a property, but for the name of the object itself. This does not seem to work"

import { Book, Movie } from '../models'  const getItems = (type, itemId) => [type].findById(itemId)  
https://stackoverflow.com/questions/65543205/in-node-js-and-mongoose-how-can-i-use-a-variable-in-place-of-a-model-name January 03, 2021 at 03:28AM

没有评论:

发表评论