i have a problem with adding a collection into my database in mongodb atlas.
I have managed to import this collection before but i accidentally deleted it and now i can't upload it again. there is no error in my terminal. There for i don't know what is wrong with my code.. (image of my code and terminal are attached below)
There is anyone who might know why is this can happen?
EDIT
I tried to open a new database and my all the collections was imported to it and once again, only the product collection doesn't
//////////////////////////////////
/* require('dotenv').config({ path: '/.env' }) */
const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '..', '.env') })
console.dir(process.env.MONGO_URI)
const mongoose = require('mongoose')
const connectDB = async () => {
try {
mongoose.connect(process.env.MONGO_URI, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('MongoDB connection SUCCESS')
} catch (error) {
console.error('MongoDB connection FAIL')
process.exit(1)
}
}
console.dir(process.env.MONGO_URI)
module.exports = connectDB
////////////////////////////////////////////////////////////////
require('dotenv').config()
const productsData = require('./data/products')
const connectDB = require('./config/db')
const Product = require('./models/product')
connectDB()
const importData = async () => {
try {
/* Product.deleteMany({}) */
Product.insertMany(productsData)
console.dir('Data Imported Successfuly')
process.exit()
} catch (error) {
console.log(error)
console.error('Error Ocured In Imported Data Process', error)
process.exit(1)
}
}
importData()
my model schema
const mongoose = require('mongoose')
const products = require('../data/products')
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
module.exports = mongoose.model('Products', productSchema)
my code and terminal image
Product.insertMany(productsData) returns a promise, but you aren't waiting for that promise to finish before exiting the process. Add an await before it and you should be okay.
Try this to create your schema instead
const { Schema } = mongoose;
const productSchema = new Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
countInStock: {
type: Number,
required: true,
},
imageUrl: {
type: String,
required: true,
},
})
const Product = mongoose.model("Product", productSchema);
Product.createCollection();
Related
I am creating a mongoose model called User. Then when I import the model on the two different controllers the mongoose show me the error 'OverwriteModelError: Cannot overwrite User model once compiled. at Mongoose.model'
Please help me if there is any one who face this error before.
My User Model
User.js
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
min: 2,
max: 100,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 5,
},
city: String,
state: String,
country: String,
occupation: String,
phoneNumber: String,
transactions: Array,
role: {
type: String,
enum: ["user", "admin", "superadmin"],
default: "admin",
},
},
{ timestamps: true }
);
const User = mongoose.model('User', UserSchema) ;
export default User;
`
The controllers
Client.js
`
import User from "../models/User.js";
export const getCustomers = async (req, res) => {
try {
const customers = await User.find({ role: "user" }).select("-password");
res.status(200).json(customers);
} catch (error) {
res.status(404).json({ message: error.message });
}
};
`
General.js
`
import User from '../models/user.js'
export const getUser = async (req, res) => {
try {
const { id } = req.params;
const user = await User.findById(id);
res.status(200).json(user);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
`
Try to check if the model is already declared before exporting it:
const User = mongoose.models.User || mongoose.model('User', UserSchema);
export default User;
This is my user schema :
import mongoose from "mongoose";
const { Schema } = mongoose;
//Address Schema
const addressSchema: mongoose.Schema = new Schema({});
//Talk about token saving planning
const userSchema: mongoose.Schema = new Schema(
{
name: {
type: String,
trim: true,
required: true,
},
username: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
required: true,
unique: true,
},
mobile_number: {
type: Number,
trim: true,
required: true,
unique: true,
},
password: {
type: String,
required: true,
min: 9,
max: 30,
},
picture: {
//AWS return object as response after upload
type: {},
//we will not provide any default
//default will be set in frontend
},
},
{ timestamps: true }
);
export default mongoose.model("User", userSchema);
Is there any way or anyone know how to create new database when newuser register in Nodejs & Express mongoose.
I am making a crm , I want to create separate database for every user who register.
var MongoClient = require('mongodb').MongoClient;
//Create a database named "userName":
userCollection.foreach(name => {
var url = "mongodb://localhost:27017/"+ name;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
}
Yes, Its possible in mySql !! and You can try it mongoose sequelize node js
const sequelizedb = new Sequelize("", MysqlInfo.username, MysqlInfo.password, {
host: MysqlInfo.dbhost,
dialect: "mysql"
});
let dbcreation = "CREATE DATABASE `" + username + "`;";
sequelizedb.query(dbcreation).then(res => {
const newDBconnection = new Sequelize(
"mysql://" +
MysqlInfo.username +
":" +
MysqlInfo.password +
"#" + MysqlInfo.dbhost + ":3306/" +
schooldbname
);
newDBconnection
.authenticate()
.then(() => {
})
I try to create a relation between 2 tables with Sequelize in NodeJS for MariaDB.
I have 2 tables order and local, the table order needs one of the information of the table local.
The order table contains information about an order (id: 1, type: Jacket, color: blue, tracking_number: TR123)
The table local contains information about the place where the order is stored (address: 20 rue madeline, city: Paris)
I tried to link the two tables but it does not work, the foreing key is not created
models/order.js
module.exports = (sequelize, DataTypes) => {
const Order = sequelize.define('order', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
trackingNumber: {
type: DataTypes.STRING,
allowNull: false
},
type: {
type: DataTypes.STRING(50),
allowNull: false
},
color: {
type: DataTypes.STRING(50),
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
tel: {
type: DataTypes.STRING(10),
allowNull: false
}
}, {
timestamps: true,
createdAt: true,
updatedAt: 'updateTimestamp'
})
Order.associate = function (models) {
Order.hasOne(models.local);
}
return Order;
}
models/local.js
module.exports = (sequelize, DataTypes) => {
const Local = sequelize.define('local', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
adress: {
type: DataTypes.STRING,
allowNull: false
},
informations_about: {
type: DataTypes.STRING,
allowNull: false
},
contact: {
type: DataTypes.STRING,
allowNull: false
},
city: {
type: DataTypes.STRING,
allowNull: false
},
zip: {
type: DataTypes.STRING(5),
allowNull: false
},
}, {
timestamps: true,
createdAt: true,
updatedAt: 'updateTimestamp'
})
return Local;
}
app.js
// Imports
const express = require('express')
const morgan = require('morgan')
const db = require('./database')
const sequelize = require('./database').sequelize;
var apiRouter = require('./apiRouter.js').router;
var helmet = require('helmet');
const app = express()
const port = process.env.PORT || 3000;
// Init server
app.use(morgan('combined'))
// Parser config
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// Security API
app.use(helmet());
app.disable('x-powered-by');
app.use(({ res }) => {
res.status(404).json({ message: "404 Not Found" })
})
db.sequelize.authenticate()
.then(_ => console.log("La connexion à bien été établie."))
.catch(error => console.log(`error ${error}`))
db.sequelize.sync({ force: true })
.then(_ => {
console.log("Base de donnée synchronisée.")
app.use('/api/', apiRouter);
})
app.listen(port, () => {
console.log("Server is up and listening in " + port)
})
database.js
const fs = require('fs')
const path = require('path')
const { Sequelize } = require('sequelize')
const db = {}
const models = path.join(__dirname, 'models') // correct it to path where your model files are
const sequelize = new Sequelize(
'',
'',
'',
{
host: 'localhost',
dialect: 'mariadb',
dialectOptions: {
useUTC: false, // for reading from database
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
logging: false
}
)
var basename = path.basename(module.filename)
fs
.readdirSync(models)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
})
.forEach(function (file) {
const model = require(path.join(__dirname + '/models', file))(sequelize, Sequelize.DataTypes)
db[model.name] = model
})
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
db.Sequelize = Sequelize // for accessing static props and functions like Op.or
db.sequelize = sequelize // for accessing connection props and functions like 'query' or 'transaction'
module.exports = db
Despite the associate function in the model/order.js it does not work, I have no key in my order table
You have to manually call all associate functions in order to register associations between models and only after all models are already registered in the Sequelize instance. You can look at my other answer to see how you can do it.
And please show the content of database module and then I probably correct my answer or append more useful tips.
I am trying to create a sample API of restaurants using POST but after starting API and loading it into Postman it does not show results.
router.js
const express = require('express');
const restaurantController = require('../Controllers/restaurantData');
const router = express.Router();
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
module.exports = router;
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const apiRouter = require('./Routes/router');
const port = 4005;
const app = express();
app.use(bodyparser.json());
app.use('/api', apiRouter);
mongoose.connect(
'mongodb://127.0.0.1:27017/sample',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
}).catch(error => {
console.log(error);
});
restaurant.js (Controller)
const restaurants = require('../Models/restaurantData');
exports.getfilter = (req, res) => {
const city_name = req.body.city_name;
const cost = req.body.cost;
restaurants.find({
city_name: city_name,
cost: cost
}).then(result => {
res.status(200).json({
message: "Filtered Data",
result
})
}).catch(error => {
res.status(500).json({
message: error
})
})
}
restaurantData.js (Model)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
I think mostly it is the router problem but trying to know where? So, share any ideas. Thank You.
This request handler:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
Does not actually call the getfilter function so nothing is ever sent from the POST request. You can fix that by either doing this:
router.post('/restaurantFilter', restaurantController.getfilter);
or this:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter(req, res);
});
Then, it looks like you also have to property export and import that getfilter() function. You appear to export it just fine in restaurant.js:
exports.getfilter = (req, res) => { ... });
But, you don't seem to be importing the controller properly as you're doing this:
const restaurantController = require('../Controllers/restaurantData');
When it looks like you should be doing this:
const restaurantController = require('../Controllers/restaurant.js');
so that you're assigning the controller the object that actually has the getfilter method on it.
So I'm currently learning how to build a Rest API with Node Js and MongoDB, so naturally I've been following some tutorials, and when the time came, I've setup an example but it doesn't work.
I have 2 main files, app.js and historic.js (model).
On app.js I have the following:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
app.use(bodyParser.json());
Historic =require('./models/historic');
// Connect to Mongoose
mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
var db = mongoose.connection;
console.log('Here');
db.on('error', function(err){
if(err){
console.log(err);
throw err;
}
});
db.once('open', function callback () {
console.log('Mongo db connected successfully');
});
app.get('/', (req, res) => {
res.send('Please use /api/historic');
});
app.get('/api/historics', (req, res) => {
Historic.getHistorics((err, historic) => {
if(err){
throw err;
}
res.json(historic);
});
});
app.listen(27017);
console.log('Running on port 27017...');
Then on my model I have the following:
const mongoose = require('mongoose');
// Historic Schema
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
const Historic = module.exports = mongoose.model('Historic', historicSchema);
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
Whenever I try to access http://localhost:27017/api/historics/ I only get: [].
I know that I have data on my DB as you can see on the image:
data on DB test
Any tips?
According to Docs http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html the callback should be at least the 2nd parameter of the .find method.
Try to replace
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
to
// Get Historics
module.exports.getHistorics = (callback, limit) => {
var query = Historic.find({});
query.limit(limit);
query.exec(callback);
}
I've been told the solution and it works.
Old Code:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
Solution:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
}, {collection: 'historic'});
I needed add the collection name that was defined on Mongoose