Sequelize umzug migrations Error: Invalid umzug storage - umzug

when I am run this code it showing error Invalid umzug storage.
the code are given bellow:
const { Umzug } = require('umzug');
const db = require('../../storage/models');
const umzug = new Umzug({
storage: 'Sequelize',
storageOptions: {
sequelize: db.sequelize, // here should be a sequelize instance, not the Sequelize module
modelName: 'SequelizeMeta',
columnName: 'name'
},
migrations: {
path: '../../storage/models'
},
logger: console,
});
exports.dbmigrate = async (req, res, next) => {
const executed = await umzug.executed();
res.send(executed);
};

Updated Umzug migration tool has some changes in the syntax. I have modified the code you posted. Please try with this code. It should work.
Reference Link: Docs
const {
Umzug,
SequelizeStorage
} = require('umzug');
const db = require('../../storage/models');
const sequelize = db.sequelize;
const umzug = new Umzug({
storage: new SequelizeStorage({ sequelize }),
storageOptions: {
sequelize: db.sequelize, // here should be a sequelize instance, not the Sequelize module
modelName: 'SequelizeMeta',
columnName: 'name'
},
migrations: {
path: '../../storage/models'
},
logger: console,
});
exports.dbmigrate = async (req, res, next) => {
const executed = await umzug.executed();
res.send(executed);
};

Related

how to handle image upload in the mern stack using multer?

Im creating a MERN stack application and in the react front end, i intend to have a form to add a product, the form is going to have a lot of inputs including an image upload option. I want to know how to handle the image upload from the express side using Multer. i have used their documentation but im not sure whether the code i wrote is correct. I also haven't created the front end yet, so i am currently using postman to test the api. How do i test whether the image upload functionality is working using postman? I would be posting the code i have written so far for context.
Product model:
const mongoose = require('mongoose')
const ProductSchema = new mongoose.Schema({
name:{
type: String,
required: [true, 'please provide a product name'],
maxlength: 20,
minlength: 3
},
category: {
type: String,
required: [true, 'please provide a category'],
maxlength: 20,
minlength: 3
},
quantity: {
type: Number,
required: [true, 'please provide the quantity']
},
price: {
type: Number,
required: [true, 'please provide the price']
},
description: {
type: String,
required: [true, 'please provide the description'],
trim: true
},
image: {
type: String
},
createdBy: {
type: mongoose.Types.ObjectId,
ref: 'User',
required: [true, 'Please provide the user'],
}, },
{ timestamps: true } )
module.exports = mongoose.model('Product', ProductSchema)
file upload.js:
const multer = require('multer')
const { v4: uuidv4 } = require('uuid')
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, '../uploads')
},
filename: function(req, file, cb){
cb(null, uuidv4() + '-' + Date.now() + path.extname(file.originalname) )
}
})
const fileFilter = (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
if(allowedTypes.includes(file.mimetype)) {
cb(null, true)
}else(
cb(null, false)
)
}
const upload = multer({storage, fileFilter})
module.exports = upload
Product router:
const express = require('express')
const router = express.Router()
const upload = require('../utils/fileUpload')
const {getAllProducts, createProduct, getProduct, updateProduct, deleteProduct} = require('../controllers/products')
router.route('/').post(upload.single('image'), createProduct).get(getAllProducts)
router.route('/:id').get(getProduct).patch(updateProduct).delete(deleteProduct)
module.exports = router
Product controller:
const Product = require('../models/Product')
const { StatusCodes } = require('http-status-codes')
const { BadRequestError, NotFoundError } = require('../errors')
const createProduct = async (req, res) => {
req.body.createdBy = req.user.userId
const product = await Product.create({...req.body, image: req.file})
res.send('create Product')
}
const getAllProducts = async (req, res) => {
res.send('get All products')
}
const getProduct = async (req, res) => {
res.send('get product')
}
const updateProduct = async (req, res) => {
res.send('update product')
}
const deleteProduct = async (req, res) => {
res.send('delete product')
}
module.exports = {
getAllProducts, createProduct, getProduct, updateProduct, deleteProduct
}
You can change the parameter type to file from postman to try uploading files when sending a request :

expressJS is preventing me to post a resource

I'm trying to build a mini app in express, the "database" I'm using is a local array object file, I can retrieve resources from this "database" but for some reason I'm not able to post (push) a new object to this object array. This is how the code looks like:
server.js:
const express = require('express');
const app = express();
const userRouter = require('./routes/user.js');
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.text());
app.use('/user', userRouter);
app.listen(3000, () => console.log(`listening at ${port}`));
user.js:
const express = require('express');
const BBDD = require('./BBDD.js');
const userRouter = express.Router();
userRouter.get('/:guid', (req, res, next) => {
const { guid } = req.params;
const user = BBDD.find(user => user.guid === guid);
if (!user) res.status(404).send()
res.send(user);
next();
});
userRouter.post('/', (req, res, next) => {
let user = {};
user.name = req.body.name;
user.id = req.body.id;
BBDD.push(user);
next();
});
module.exports = userRouter;
And this is my local "database" file I want to perform logical CRUD operations:
BBDD.js
const BBDD = [{
index: 0,
guid: "1",
name: "Goku"
},
{
index: 1,
guid: "2",
name: "Vegeta"
},
];
module.exports = BBDD;
this is how I try to post a new resource, and this is the error I get:
It seems to be in order, but it won't work and can't find the bug.
Remove the next and send a response .express is having trouble finding the next matching handler because there is none

(redis-om & fastify) this.writeEntity is not a function

I'm learning to use the Redis for my backend database and I would like to try using redis-om for fastify not sure whether they are compatible or not, but I got error.
I use service of app.redislabs.com
I don't know what I just messed up? And how can I fix the problem?
server.js
const { createCar, createIndex } = require("./redis");
app.post("/add", async (req, res) => {
await createIndex();
const { make, model, image, description } = req.body;
const data = { make, model, image, description };
await createCar(data);
res.code(200).send('ok');
});
const PORT = 5000;
app.listen(PORT, function (err) {
if (err) {
app.log.error(err);
process.exit(1);
}
});
redis.js
const { Client, Entity, Schema, Repository } = require("redis-om");
const client = new Client();
const connect = async () => {
if (!client.isOpen()) {
await client.open("redis://default:password#localhost:6379");
} else {
console.log("CONNECTED");
}
};
class Car extends Entity {}
let schema = new Schema(
Car,
{
make: { type: "string" },
model: { type: "string" },
image: { type: "string" },
description: { type: "string" },
},
{ dataStructure: "JSON" }
);
const createCar = async (data) => {
await connect();
const repository = new Repository(schema, client);
const car = repository.createEntity(data);
const id = await repository.save(car);
return id;
};
const createIndex = async () => {
await connect();
const repository = new Repository(schema, client);
await repository.createIndex();
};
module.exports = {
createCar,
createIndex,
};
My JSON Body
You cannot call new on Repository. This is a breaking change I introduced in version 0.2.0 of Redis OM. There are a couple of others that are documented in the CHANGELOG.
Call const repository = client.fetchRepository(schema) instead, as shown here. Unfortunately, there are some videos and blogs that have the older syntax and so this crops up from time to time.
Thanks for using my library!

Getting Error 500 (general-error) while uploading files in feathersjs

I am getting this error on Postman when I send request for uploading files on Feathersjs:
{
"name": "GeneralError",
"message": "ENOENT: no such file or directory, open 'public/uploads/pic'",
"code": 500,
"className": "general-error",
"data": {},
"errors": {}
}
My uploads.service.js:
const {Uploads} = require('./uploads.class');
const createModel = require('../../models/uploads.model');
const hooks = require('./uploads.hooks');
const multer = require('multer');
const storage = multer.diskStorage({
destination: (_req, _file, cb) => cb(null, 'public/uploads'), // where the files are being stored
filename: (_req, file, cb) => {
console.log(_req.body);
//cb(null, ${_req.body.name});
cb(null, `${_req.body.name}`); //
}, // getting the file name
});
const uploads = multer({
storage,
limits: {
fieldSize: 1e8,
fileSize: 1e7,
},
});
module.exports = function(app) {
const options = {
Model: createModel(app),
paginate: app.get('paginate'),
multi: true,
};
// Initialize our service with any options it requires
app.use(
'/uploads',
uploads.array('files'),
(req, _res, next) => {
const {method} = req;
if (method === 'POST' || method === 'PATCH') {
console.log(req.files);
console.log(req.body);
req.feathers.files = req.body.files;
const body = [];
for (const file of req.files)
body.push({
name: req.body.name,
newNameWithPath: file.path,
});
req.body = method === 'POST' ? body : body[0];
}
next();
},
new Uploads(options, app),
);
// Get our initialized service so that we can register hooks
const service = app.service('uploads');
service.hooks(hooks);
};
This is my uploads.model.js:
module.exports = function(app) {
const modelName = 'uploads';
const mongooseClient = app.get('mongooseClient');
const {Schema} = mongooseClient;
const schema = new Schema(
{
name: {type: String, required: true},
},
{
timestamps: true,
},
);
// This is necessary to avoid model compilation errors in watch mode
// see https://mongoosejs.com/docs/api/connection.html#connection_Connection-deleteModel
if (mongooseClient.modelNames().includes(modelName)) {
mongooseClient.deleteModel(modelName);
}
return mongooseClient.model(modelName, schema);
};
I really cannot figure out where exactly the problem is. According to me it is supposed to make the folder automatically when I upload the file.
I would really appreciate some help. Thank you in advance.
It was my own mistake. I made the uploads folder inside public folder myself and now it's working.

Adding mongoose schema model to express results in error 500

I have react app that stores data via axios to a mongoose server. It worked perfect until I wanted to add an extra schema for different data. My schema models are separated so I thought to just add another one called PartyList.js.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Define collection and schema for Items
var PartyList = new Schema({
name: {
type: String
},
song_id: {
type: String
},
port: {
type: Number
}
},{
collection: 'party'
});
module.exports = mongoose.model('PartyList', PartyList);
This is the code in my app.js.
const config = require('./database/DB');
const ServerPortRouter = require('./routes/ServerPortRoutes');
mongoose.connect(config.DB).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database' +err)
});
app.use('/serverport', ServerPortRouter);
This is how I import it and try to run it (called ServerPortRoutes.js). After running a part of my application that uses this route I get a 500 (Internal Server Error). My server tells me ReferenceError: PartyList is not defined which is defined 3 lines above.
const ServerPort = require('../models/ServerPort');
const PartyList = require('../models/PartyList');
ServerPortRouter.route('/add-party').post(function (req, res) {
const PartyList = new PartyList(req.body);
PartyList.save()
.then(PartyList => {
res.json('Server added successfully');
})
.catch(err => {
res.status(500).send("unable to save to database");
});
});
The problem looks to be you are redefining a const . In your route change to const partyList = new PartyList(req.body); Then use partyList as your variable