I've this project folder structure:
And I'm trying to import my user schema in my user ctrl but when i start nodemon users.ctrl.js gives me this error:
const {Users} = require('users.schema');
^
SyntaxError: Unexpected token
This is the user schema:
const mongoose = require('mongoose');
const validator = require('validator');
// {
// email: 'andrew#example.com',
// password: 'adpsofijasdfmpoijwerew',
// tokens: [{
// access: 'auth',
// token: 'poijasdpfoimasdpfjiweproijwer'
// }]
// }
var Users = mongoose.model('Users', {
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
required: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
module.exports = {Users}
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
Where am I wrong? Is there something that escapes me?
By default node corresponds to /node_modules where the node packages are stored. Hence use relative path names to access the file require(./filename).
I solved the problem:
On this current pc that i'm using i had node version number 5.0.7 . To use the new ecma6 features i need to install v 8.0....
After installing the version I solved the problemAfter installing the version I solved the 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();
I keep getting a 404 when I am posting to a route. I am using MongoDB, express and React Native. I have created the Schema, actions and router.
The Schema is below:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Edible Schema
const EdiblesSchema = new Schema({
name: {
type: String,
required: true
},
price: {
type: String,
required: true
},
strength: {
type: String,
required: true
},
purchasedLocation: {
type: String,
required: true
},
effects: {
type: String,
required: true
},
strain: {
type: String,
required: true
},
});
module.exports = Edibles = mongoose.model("edibles", EdiblesSchema);
Then the post router is below:
const express = require("express");
const router = express.Router();
const keys = require("../../config/keys");
// Load edibles model
const Edibles = require("../../models/edibles");
// #route POST api/users/edibles
// #desc Add an edible to the users collection
// #access Public
router.post ('/edibles', (req, res) => {
if (res.status === 200) {
const newEdible = new Edibles({
name: req.body.name,
price: req.body.price,
strength: req.body.strength,
strain: req.body.strain,
purchasedLocation: req.body.purchasedLocation,
effects: req.body.effects,
})
} else {
return res.status(400).json({ email: "Thats not going to get you high" });
} newEdible
.save()
.then( edibles => res.json(edibles))
.catch(err => console.log(err))
});
module.exports = router;
Then the finale we have the handleSubmit to send the users info to the api endpoint.
const handleSubmit = (response) => {
console.log("EDIBLES", name, strength, price, effects, strain)
dispatch(setEdible(payload))
if (response === 200) {
axios
.post(edibleApi, payload)
console.log("PAYLOAD", edibleApi, payload, setEdible)
// navigation.navigate("Dashboard")
} else {
console.log("WRONG", edibleApi, payload, setEdible);
console.log("userEdibles", userEdibles)
}
}
I am really lost with this... Please help!
The issue was that I was using the wrong endpoint. I worked this out by using the express-list-routes by adding it to my server.js file.
const expressListRoutes = require('express-list-routes');
const router = express.Router();
console.log("Now we cooking with gas", expressListRoutes(app, { prefix: '/api/v1' })))
That console.log must be added to the console.log that indicates if your server is running or not....
I am using MongoDB, Mongoose, Elasticsearch and Mongoosastic on a Node project. I have a MongoDB Atlas database and a local Elasticsearch database which are mapped together. When I create a new Document in MongoDB it is created in ES as well, and when I delete it in Mongo it is deleted in ES too. So everything works until this point.
What I did next is, I added an update route to update specific documents in Mongo. They do get updated but the changes are not reflected in ES because I might be missing something. Does anyone have any ideas?
Here is the Model/Schema in donation.js:
const mongoose = require('mongoose');
const mongoosastic = require('mongoosastic');
const Schema = mongoose.Schema;
const donationSchema = new Schema({
donorUsername: {
type: String,
required: true,
es_indexed:true
},
bankName: {
type: String,
required: true,
es_indexed:true
},
qualityChecked: {
type: String,
required: true,
es_indexed:true
},
usedStatus: {
type: String,
required: true,
es_indexed:true
},
}, { timestamps: true });
donationSchema.plugin(mongoosastic, {
"host": "localhost",
"port": 9200
});
const Donation = mongoose.model('Donation', donationSchema , 'donations');
Donation.createMapping((err, mapping) => {
console.log('mapping created');
});
module.exports = Donation;
Here are the create and update functions/routes in donationController.js:
const donation_create_post = (req, res) => {
console.log(req.body);
const donation = new Donation(req.body);
donation.save()
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}
const donation_update = (req, res) => {
const filter = { donorUsername: req.body.donorUsername };
const update = { bankName: req.body.bloodbankName,
qualityChecked: req.body.qualityChecked,
usedStatus: req.body.usedStatus };
Donation.findOneAndUpdate(filter, update)
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}
Solved it. Added {new: true} in Donation.findOneAndUpdate(filter, update, {new: true}).
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