jeka-kiselyov / fastify-mongoose-api Goto Github PK
View Code? Open in Web Editor NEWFastify plugin to expose API for Mongoose MongoDB models
Home Page: https://fastify-mongoose-api-app.herokuapp.com/
License: MIT License
Fastify plugin to expose API for Mongoose MongoDB models
Home Page: https://fastify-mongoose-api-app.herokuapp.com/
License: MIT License
It will be great if we have options for prehandler and posthandler .
Where we can do fallowing
The schema will not work properly
const mongoose = require('mongoose');
const mongooseConnection = await mongoose.createConnection(MONGODB_URL, { useNewUrlParser: true });
const authorSchema = mongoose.Schema({
firstName: String,
lastName: String,
aGoodMan: Boolean,
biography: String,
created: { type: Date, default: Date.now }
});
You can save a doc with the property aGoodMan
equal to true
.
It will not be possible to change it to false
then.
The reason is in the method async apiPut
of class DefaultModelMethods
.
async apiPut(data) {
//// this points to document (schema.methods.)
this.schema.eachPath((pathname) => {
if (data[pathname]) {
this[pathname] = data[pathname];
} else if (data[pathname] === null) {
this[pathname] = undefined;
}
});
await this.save();
}
It's better to change the method of checking value to something like this:
async apiPut(data) {
//// this points to document (schema.methods.)
this.schema.eachPath((pathname) => {
if (data[pathname] !== undefined) {
this[pathname] = data[pathname];
} else if (data[pathname] === null) {
this[pathname] = undefined;
}
});
await this.save();
}
It would be awesome if projections could be defined for certain routes (such as the list route) or if they could be sent in via route query params. Do you have any thoughts on the best way to go about this / any interest in adding it as a feature? I'd be happy to contribute.
Why would it be useful? Mainly for performance reasons. I have some fields that are really large that I would like to have only display on the "find by id" route but not on the "list" route.
EDIT:
first pass at "hacking" it in there. I feel like there's probably a better way than putting a "default list projection" on the model but it works:
// in my model
MySchema.set('listProjection', { fieldIDontWant1: 0, otherFieldIDontWant: 0 });
// in APIRouter.js
async getListResponse(query, request, reply) {
const offset = request.query.offset ? parseInt(request.query.offset, 10) : 0;
const limit = request.query.limit ? parseInt(request.query.limit, 10) : 100;
const sort = request.query.sort ? request.query.sort : null;
const filter = request.query.filter ? request.query.filter : null;
const search = request.query.search ? request.query.search : null;
const match = request.query.match ? request.query.match : null;
const populate = request.query.populate ? request.query.populate : null;
const projection = this._model.schema.get('listProjection');
if (projection) {
query.projection(projection);
}
// rest of function as normal, could reorder it however you want
Hello! This is awesome package!
I did deep research until finally I found this package!
I love it!
So dear Jeka, can you help to understand how to integrate the plugin with fastify-swagger?
it doesn't see the list of routes defined by the package.
Since @types/fastify-mongoose-api does not exist, I cannot use it with Typescript. Is there any plan to add Typescript support in future?
Hi!
I followed your instructions, but When I run the application it throws the error:
ReferenceError: mongooseConnection is not defined
What should I do to avoid it?
Main.js file:
const Fastify = require('fastify');
const fastifyMongooseAPI = require('fastify-mongoose-api');
const fastifyFormbody = require('fastify-formbody');
const fastify = Fastify();
fastify.register(fastifyFormbody);
fastify.register(fastifyMongooseAPI, {
models: mongooseConnection.models,
prefix: '/api/',
setDefaults: true,
methods: ['list', 'get', 'post', 'patch', 'put', 'delete', 'options']
});
fastify.ready();
fastify.listen(4050);
model is placed in file: /models/Video.js
Video.js:
const mongoose = require('mongoose');
const MONGODB_URL = 'mongodb://localhost:27017/controlSurfaceDB'
const mongooseConnection = mongoose.createConnection(MONGODB_URL, { useNewUrlParser: true });
//Create Schema and Model
const videoSchema = mongoose.Schema({
title: {
type: String,
required: true
},
url: {
type: String,
required: true
}
});
const Video = mongooseConnection.model('Video', videoSchema);
`'use strict'
const { port, dbConfig } = require("./configuration");
// Require the framework and instantiate it
const fastifyMongooseAPI = require('fastify-mongoose-api');
const fastifyFormbody = require('fastify-formbody');
const mongoose = require('mongoose');
const fastify = require('fastify')();
const init = async () => {
const mongooseConnection = await mongoose.connect('mongodb://auth_db:27017/auth', { useNewUrlParser: true, useUnifiedTopology: true });
const authorSchema = mongoose.Schema({
firstName: String,
lastName: String,
biography: String,
created: { type: Date, default: Date.now }
});
const Author = mongooseConnection.model('Author', authorSchema);
const bookSchema = mongoose.Schema({
title: String,
isbn: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' },
created: { type: Date, default: Date.now }
});
const Book = mongooseConnection.model('Book', bookSchema);
await fastify.register(fastifyFormbody);
await fastify.register(fastifyMongooseAPI, {
models: mongooseConnection.models,
prefix: '/',
setDefaults: true,
methods: ['list', 'get', 'post', 'patch', 'put', 'delete', 'options']
});
await fastify.ready();
await fastify.listen(port, '0.0.0.0');
}
init()
`
Frontend
async function saveAuthor () { const formData = new FormData(); formData.append('title', text.value); await axios.post('http://localhost/auth/books', formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}) }
Status Code: 415 Unsupported Media Type
I have been struggling with this for several days now, I need your help. I can't figure out what the problem is
UPD
I was able to send a valid request only with new URLSearchParams (), with FormData the request could not be sent
async function saveAuthor () { const formData = new URLSearchParams(); formData.append('title', text.value); await axios.post('http://localhost/auth/books', formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) }
Everything else works OK except for DELETE method.
I am not sure, maybe it's related to some deprecation.
I use:
fastify-mongoose-api": ^1.2.20
mongoose": "^7.6.3
I am running into an issue generating CRUD models for a very basic model. All routes work as normal except using the GET method at the root of the model - which is intended to list all collection objects matching that model type.
await server.register(fastifyMongooseAPI, {
models: mongoose.models,
prefix: '/api/',
setDefaults: true,
methods: ['list', 'get', 'post', 'patch', 'put', 'delete', 'options']
});
req: {
"method": "GET",
"url": "/api/servers",
"hostname": "localhost:1600",
"remoteAddress": "127.0.0.1",
"remotePort": 52945
}
reqId: "10aa48ee-6f6c-44d0-XXX"
[1645364211639] ERROR (13016 on DESKTOP-H0SUPE1): Query was already executed: server.find({})
MongooseError: Query was already executed: server.find({})
at model.Query._wrappedThunk [as _find] (C:\XXX\node_modules\.pnpm\[email protected]\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19)
at C:\xxx\node_modules\.pnpm\[email protected]\node_modules\kareem\index.js:372:33
at processTicksAndRejections (node:internal/process/task_queues:78:11)
[1645364211641] INFO (13016 on DESKTOP-H0SUPE1): request completed
res: {
"statusCode": 500
}
responseTime: 7.673600003123283
reqId: "XXX-8cd2b731b4b6"```
I didn't define POST, but it took a post request when I got it.ย
fastify.register(fastifyFormbody);
fastify.register(fastifyMongooseAPI, {
models: mongoose.models,
prefix: '/api/items',
setDefaults: true,
methods: ['get', 'patch', 'put', 'delete', 'options']
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.