Here's my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostsSchema = new Schema({
userId: String,
postId: String,
title: String,
description: String,
tags: { many: String, where: String, what: String },
date: { type: Date, default: Date.now },
}, { collection : 'posts'});
const Posts = mongoose.model('Post', PostsSchema);
module.exports = Posts;
Here's my route with the query:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Posts = require('../models/Posts');
router.get('/', (req, res, next) => {
const refreshOrLoadMore = params.refreshOrLoadMore || '';
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10, (err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}
});
The if statement returns true and the first console.log is triggered. But after that none of the other console.logs are triggered and just nothing happens. No data is being send and no error is being send.
So my guess is, that i did something wrong with the Schema, but i did it just as i did my other ones and they do work.
Can someone point out where i went wrong?
Thanks in advance!
Try this
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10)
.exec((err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}
Related
I have a node application using mongo db and Im trying to send back the MongoServerError if there is an error but i only can console.log it like i did in wsService.js
here are my code:
app.js
const errors = require('./helpers/errorHandler');
const users = require('./controllers/wsController')
app.use(errors.errorHandler)
app.use('/ws', ws)
wsModel.js:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const wsSchema= new Schema({
wsKey1: {
type: String,
required: true,
unique: true,
},
wsKey2: {
type: String,
required: true,
}
});
const WS = mongoose.model("ws", wsSchema);
module.exports = WS;
wsService.js:
const WS = require('../models/wsModel')
const createNewInstance= async (object)=>{
console.log(object)
var newInstance = new WS(object)
newInstance.save( (err, session)=> {
if (err) console.log(err);
console.log(session.wsKey1+ " saved to Open Sessions collection.");
return session
});
return {
"session":newInstance
}
}
module.exports = {
createNewInstance,
};
and my controller.js:
router.post('/createNewInstance', (req, res, next)=>{
wsService.createNewInstance(req.body).then(
(session) =>res.send(session)
).catch(
err => next(err)
)
})
exports.clearHours = (req, res, next) => {
Hour
.find({ user: req.body.userId })
.then(hour => {
for (let i=0;i<hour.length;i++) {
hour[i].hours = 0;
}
return hour.save()
})
.then(result => {
res.status(200).json({message: 'Working hours have been successfully updated.'});
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
})
};
I am trying to save the formatted array on the database and I get this error. The updated code is passed properly but when I am trying to save the array it comes up with this error. Any ideas why?
This is my hour model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const hourSchema = new Schema ({
day: {
type: String,
required: true
},
hours: {
type: Number,
required: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
});
module.exports = mongoose.model('Hour', hourSchema);
It seems you are fetching the document into memory and re-setting the hour field to 0, better you can run an update query into the database itself.
On top require mongoose -
const mongoose = require('mongoose');
Below is clearHours method refactored.
exports.clearHours = async (req, res, next) => {
try {
const query = {
user: mongoose.Types.ObjectId(req.body.userId)
};
const update = {
$set: {
hours: 0
}
};
await Hour.update(query, update).exec();
res.status(200).json({message: 'Working hours have been successfully updated.'});
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
It does not return anything back (hang state) and i see in console
{ _id: 5f05d1527de7984a2c998385, name: 'alexa', age: 12 }. I tried both method promise and callback but still same. Can you guess what could be the issue?
const express = require('express');
const app = express();
const mongoose = require('mongoose');
app.use(express.json());
const TestModel = mongoose.model(
'test',
new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
}),
);
app.post('/test', async (req, res, next) => {
const testUser = req.body;
const Test = new TestModel(testUser);
console.log(Test);
/* Test.save(function (err, doc) {
if (err) {
return res.json({ message: 'something went wrong' });
}
res.json(testUser);
}); */
await Test.save();
res.json(testUser);
});
app.listen(4000, () => {
console.log('playground is up');
});
I'm learning the MERN stack and encountered an issue on the edit route of my child router.
I have the below model schemas in songs.js and students.js files:
const mongoose = require('mongoose');
const studentSchema = mongoose.Schema({
name: { type: String, required: true },
instrument: String,
songs: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Song'
}]
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
const mongoose = require('mongoose');
const songSchema = mongoose.Schema({
name: { type: String, required: true },
img: String
})
const Song = mongoose.model('Song', songSchema);
module.exports = Song
And I have songs.js and students.js files for my routers, with mergeParams set to true for my songs router const songs = express.Router({ mergeParams: true });. I'm attaching it to the students router like this:
students.use('/:id/songs', songs);
e.g., my url parameters become students/student1/songs/song1
All of my other routes are working, but on the update route of my songs router I'm getting an error "TypeError: Student.findById is not a function" when I redirect back to the song's index view. My edit and update routes
are below:
songs.get('/:songId/edit', async (req, res) => {
try {
const findSong = Song.findById(req.params.songId);
const findStudent = Student.findById = (req.params.id);
const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
res.render('songs/edit', {
student: foundStudent,
song: foundSong
})
} catch (err) {
console.log(err);
}
});
songs.put('/:songId', async (req, res) => {
try {
const updateSong = await Song.findByIdAndUpdate(req.params.songId, req.body, { new: true });
res.redirect('/students/' + req.params.id + '/songs');
} catch (err) {
console.log(err);
}
});
I'm not sure what's causing the error here, my delete route is set up similarly and is working. Would appreciate any suggestions.
In your rote (req.params.id) is not defining.
songs.get('/:songId/edit', async (req, res) => {
try {
const findSong = Song.findById(req.params.songId);
**const findStudent = Student.findById = (req.params.id);**
const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]);
res.render('songs/edit', {
student: foundStudent,
song: foundSong
})
} catch (err) {
console.log(err);
}
});
I'm using mongoose to connect mongoDB. Its a nodeJS application. Right now I'm concerned to get the data and display it in my application. However, it doesn't show any error, neither it displays any data.
Here's my server file
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
const employeeRoute = require('./routes/employee.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true })
.then(() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database' + err) }
);
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/Employees', employeeRoute);
let port = process.env.PORT || 4000;
const server = app.listen(port, function () {
console.log('Listening on port ' + port);
})
and here's my route file
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
let employees = [];
Employees.find({}, function (err, results) {
if (err) {
console.log(err);
}
else {
employees = results;
console.log(employees)
res.json(employees);
}
})
})
module.exports = employeeRoute
and lastly my employee.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
},
{ collation: 'Employees' });
module.exports = mongoose.model('Employees', Employee)
Application runs fine without any error. Before posting it to the forum, I've double checked the db and collection names.
any suggestions
It looks like you might just need to refactor your route a little bit in order to ensure you get the results you want. For example, take a look at my following example:
const express = require('express');
const employeeRoute = express.Router();
let Employees = require('../models/Employee');
employeeRoute.route('/').get(function (req, res) {
// Extract data from the request object here in order to search for employees. For example:
const name = req.body.name;
const surname = req.body.surname;
let employees = [];
// Now perform a find on your specific data:
Employees.find({ first_name: name, last_name: surname }, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
// Or you can perform a find on all employees
Employees.find({}, function(err, results) {
if (err) console.log(err);
else employees = results;
console.log(JSON.stringify(employees));
res.json(employees);
});
})
module.exports = employeeRoute
As I mentioned in my comment too, your connection may need to be changed to use the correct term: useNewUrlParser
EDIT
I also noticed that in your Employee Schema, you put collation instead of collection - see below:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Employee = new Schema({
first_name: { type: String },
last_name: { type: String },
title: { type: String },
email: { type: String },
gender: { type: String },
location: { type: String },
phone: { type: Number }
}, { collection: 'employees' });
module.exports = mongoose.model('Employees', Employee)
Try that, does it make any difference?
You are doing it wrong buddy.Here's a sample way of inserting data using mongoose.
employeeRoute.route('/').get(function (req, res) {
Employees.create({your_data}) // ex: {email:req.body.email}
.then((employee)=>{
console.log(employee)
res.json(employee);
}).catch((err)=> {
console.log(err);
res.status(400).send({message: "your message"})
})
})
module.exports = employeeRoute