this is my code in routes/blog.js
var express = require('express');
var router = express.Router();
const Blogs = require("../models/blog");
and this my code in models/blog.js
const mongoose = require('mongoose');
const mongo = require('mongodb');
const dbUrl = 'mongodb://localhost:27017/BlogDB';
mongoose.connect(dbUrl, { useNewUrlParser: true });
const db = mongoose.connection;
const Schema = mongoose.Schema;
const blogSchema = new Schema({
id: {
type: Schema.ObjectId
},
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
category: {
type: String,
required: true
},
content: {
type: String,
required: true
},
})
const Blogs = module.exports = mongoose.model("blogs", blogSchema);
//module.exports = mongoose.model("blogs", blogSchema);
I've tried some basic solutions. But still can't use npm start ,
Is there any way I can get it to work? I'm a beginner, please.
In your routes/blog.js edit 3rd line to this const Blogs = require("../views/models/blog"); should resolve your problem.
Related
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();
Can the following model for conversations and chat messages be used in production applications?
If the database grows and there will be more news, is the following approach appropriate? I am asking for advice
Conversation
const mongoose = require("mongoose");
const ConversationSchema = new mongoose.Schema(
{
members: {
type: Array,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Conversation", ConversationSchema);
Message
const mongoose = require("mongoose");
const MessageSchema = new mongoose.Schema(
{
conversationId: {
type: String,
},
sender: {
type: String,
},
text: {
type: String,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Message", MessageSchema);
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.
I try to create a dedicated mongoose createConnection. Node.js rapports:
MyModel = conn.model('Profile', profileSchema),
profileSchema is not defined. But where did I go wrong?
//my db.js
const mongoose = require('mongoose');
const conn = mongoose.createConnection = ("mongodb://localhost:27017/myDatabase"),
MyModel = conn.model('Profile', profileSchema),
m = new MyModel;
m.save(); //works;
if (process.env.NODE_ENV === 'production') {
conn = process.env.MONGODB_URI;
}
require('./profiles)
Here the rest of my model page:
// my profile.js
// JavaScript source code
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
var MyModel = mongoose.model('Profile', profileSchema);
What you have to do is
// my profile.js
// JavaScript source code
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
module.exports = mongoose.model('Profile', profileSchema);
and in your app.js file put like this
const profileInfo= require('./../model/profile.js');
There are many issues with your code, First learn how module works in javascript.
You need to export the profileSchema inorder to use inside the app.js, it should be,
const mongoose = require('mongoose');
const profileSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
});
module.exports = mongoose.model('Profile', profileSchema);
then need to import profileSchema which lies inside profile depend on your file path.
const profileSchema = require('./model/profile.js');
I'm trying to link my mlab with my models but it's throwing me an error like this:
throw new TypeError('Undefined type ' + name + 'at' + path +
^
TypeError: Undefined type undefined at required
Did you try nesting Schemas? You can only nest using refs or arrays.
In my folder models I've got:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProjectSchema = new Schema({
name: String,
email: String,
description: String,
image: {data: Buffer, contentType: String },
date: { type: Date, default: Date.now },
location: String, //{street: String, number: String, zip: String, city: String, required: true},
fixedAmount: Number, required: true,
wantedAmount: Number,
receivedAmount: Number
});
module.exports = mongoose.model('Project', ProjectSchema);
and almost the same with my UserSchema...
I have also an index.js there :
const mongoose = require('mongoose');
module.exports.connect = (uri) => {
mongoose.connect(uri);
// plug in the promise library:
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => {
console.error(`Mongoose connection error: ${err}`);
process.exit(1);
});
// load models
require('./user');
require('./project');
require('./common');
};
In my server.js :
const config = require('./config.js');
// connect to the database and load models
require('./server/models').connect(config.dbUrl);
and in my config.js:
const dotenv = require('dotenv').config();
module.exports = {
'port': process.env.PORT || 5000,
'dbUrl': `mongodb://${process.env.USER_DB}:${process.env.PASSWORD_DB}#ds123930.mlab.com:23930/kickass`,
"jwtSecret": "a secret phrase !"
}