trying to display data from mongoose schema to jade temaplate but it dosent work no matter what i try , so please help me and thanks .
first here is my book schema models/book.js
const mongoose = require('mongoose')
const schema = mongoose.Schema
const BookSchema = new schema({
title: String,
author: String,
isbn: Number,
date: { type: Date, default: Date.now},
description: String
})
module.exports = mongoose.model('Book', BookSchema)
and here is my controller for the book model
const Book = require('../models/book')
const express = require('express')
router = express.Router()
router.route('/books')
// Create a book
.post( (req, res) => {
const book = new Book()
book.name = req.body.name
book.save( (err) => {
if (err)
res.send(err)
console.log('Book created! ')
})
})
//get all books
.get( (req, res) => {
Book.find( (err, books) => {
if (err)
res.send(err)
res.render('books', {title: 'books list'})
})
})
module.exports = router
and at last here is my jade template
extends layout
block content
if books
each book in books
h1 #{book.title}
There are multiple mistakes/modifications required in your code.
while finding, its better to give {} as first input.
When rendering the book template, you are using books variable to show list of books, but you are not sending it from the route. you need to send books in res.render.
Try this:
router.route('/books')
// Create a book
.post( (req, res) => {
const book = new Book()
book.name = req.body.name
book.save( (err) => {
res.send(err)
console.log('Book created! ')
})
})
//get all books
.get((req, res) => {
Book.find({},(err, books) => {
if (err)
res.send(err)
res.render('books', {title: 'books list' , books : books})//need to send the books variable to the template.
})
})
Related
Basically I am trying to make a to-do-app which will be based on the CITY that a user submits from, if they submit from VANCOUVER, then I want there to be a collection created named VANCOUVER and the post to be submitted there, then I can collect posts from that collection, the reason being performance when I begin to add query , so I dont have to query alot of the posts if I just need info from 1 city.
I did read the docs and current I am experimenting, would love some input here.
If someone can point me to some articales or guides / good doc points, I would love that or just help me if I am going the right way , or perhaps I should be looking at the problem in a different light?
This is my current route file
const express = require('express');
const router = express.Router();
// Schema import
const postModel = require('../models/postModel');
const vancouver = require('../models/cityModel');
const toronto = require('../models/cityModel');
const victoria = require('../models/cityModel');
const mongoose = require('mongoose');
// this should return all of the posts inside of a single city
// wildcard could be vancouver or toronto for example
router.get('/:wildcard', (req, res, next) => {
req.params.wildcard.find((error, returnedDocuments) => {
if (error) return next(error);
res.json(returnedDocuments);
});
});
// this should delete a single post, via an ID identification , inside of a specific city
// the city will be set on the user side
router.delete('/:wildcard', (req, res, next) => {
req.params.wildcard.findByIdAndRemove(req.query.postid, (error, returnedDocuments) => {
if (error) return next(error);
res.json(returnedDocuments);
});
});
router.post('/:wildcard', (req, res, next) => {
req.body.wildcard.create({ post: req.body.post }, (error, returnedDocuments) => {
if (error) {
throw new Error(error);
}
});
});
module.exports = router;
the city mode is basically just the city name, and has an array for posts, these will be queried based on the category that the user wants to access
const citySchema = new mongoose.Schema(
{
name: { type: String },
posts: { type: Array }
},
{
timestamps: true
}
);
module.exports = mongoose.model('city', citySchema);
You can parameterize the model-generation:
const express = require('express');
const router = express.Router();
// Schema import
const postModel = require('../models/postModel');
const citySchema = require('../models/citySchema');
const mongoose = require('mongoose');
const getModel = (name) => mongoose.modelNames().contains(name) ? mongoose.model(name, citySchema) : mongoose.model(name)
router.get('/:wildcard', (req, res, next) => {
// You should add some validation on the wildcard before using it directly here
getModel(req.params.wildcard).find((error, returnedDocuments) => {
if (error) return next(error);
res.json(returnedDocuments);
});
});
// ...
module.exports = router;
citySchema:
const citySchema = new mongoose.Schema(
{
name: { type: String },
posts: { type: Array }
},
{
timestamps: true
}
);
module.exports = citySchema;
A thing to note is that you are risking creating arbitrarily many models and collections, which might have some performance impact as well.
So I'm trying to set this form page, the information is being sent but the database is not being created automatically, and consequently, my info is not being saved
Sorry for the long post and thanks for any feedback
This is my app.js
mongoose.connect('mongodb://localhost/cloud', {
useNewUrlParser: true
})
})
.catch(err => console.log(err));
require('./models/post');
const post = mongoose.model('post');
const app = express();
app.post('/cloud', (req, res) => {
upload(req, res, (err) => {
if (err) {
res.render('index', {
msg: err
});
} else {
console.log(req.body);
const newUser = {
title: req.body.title,
}
new post(newUser).save().catch(post => {
res.redirect('/cloud');
})
}
});
});
app.get('/cloud', (req, res) => {
post.find({})
.sort({Date: 'desc'})
.then(posts => {
res.render('cloud/cloud', {
posts: posts
});
});
});
const port = 3000;
app.listen(port, () => {
console.log(`running ${port}`);
});
Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema ({
title:{
type: String,
required: true
}
});
mongoose.model('post', postSchema);
Handlebars file
{{#each posts}}
<h4>{{title}}</h4>
{{else}}
<p>No pics found</p>
{{/each}}
You did not specify your schema property at this line of your code.
new post(newUser).save().catch(post => {
res.redirect('/cloud');
The correct way is
new post({title: new User} ).save().catch(post => {
res.redirect('/cloud');
Now, you have specify mongoose to save a new record for title.
I developed my node rest api as usual but this time it is showing some invalid error in controller.js file. The mongoose is not getting required. When I hit the API in postman, it gives the error as :
{
"error": {
"message": "Tweets is not a constructor"
}
}
I even updated my packages for the same, but nothing seems to work. Here is the snippet of my controller for tweets.js:
const mongoose = require('mongoose');
const Tweets = require('../models/tweets');
exports.get_all_tweets = (req, res, next) => {
Tweets.find()
.exec()
.then(docs => {
console.log(docs);
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
exports.create_tweets = (req, res, next) => {
const tweetbody = req.body;
tweetbody._id = mongoose.Types.ObjectId();
const tweet = new Tweets(tweetbody);
tweet
.save()
.then(docs => {
console.log(docs, 'Tweets');
res.status(200).json(docs);
})
.catch(err => {
console.log(err, 'error found');
res.status(500).json({
error:err
});
});
The first mongoose line is appearing blank as shown in the screenshot:
mongoose
Model for tweets.js:
const mongoose = require('mongoose');
const tweetSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
time: { type: String},
count: { type: Number}
});
module.export = mongoose.model('Tweets', tweetSchema);
please check all path and add new keyword before schema initializing
Model for tweets.js:
const tweetSchema = new mongoose.Schema({
Try this using async/await
exports.get_all_tweets = async (req, res, next) => {
const result = await Tweets.find()
res.status(200).json(result);
}
module.exports with a 's' at the end :)
I have this api route function that needs updates a topic record to include a reference of post, then save the actual post record being created. Is there a better way to do what i want to do? is it possible?
const express = require('express');
const router = express.Router();
router.post('/:id/posts', (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
Topic.findById(req.params.id)
.then(topic => {
topic.posts.push(newPost._id);
})
.catch(err => {
res.send(err);
});
//how do i save this topic record I find and push an id into.
newPost.save().then(post => res.json(post));
});
github line 33: https://github.com/wolffles/bloccit-node/blob/express/routes/api/topics.js
Question
How do you save the topic record you found and modified?
Answer
Try this out with the latest JS async await syntax.
router.post('/:id/posts', async (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
try {
await Topic.findById(req.params.id, (err, doc) => {
doc.posts.push(newPost._id);
doc.save();
});
const post = await newPost.save()
res.json(post)
} catch(err) {
res.send(err)
}
});
Let me know if this works for you.
Just save the document in the promise success of the topic return. Just like i wrote below.
Let me know if that works.
const express = require('express');
const router = express.Router();
router.post('/:id/posts', (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
Topic.findById(req.params.id)
.then(topic => {
topic.posts.push(newPost._id);
//now update the newPost
newPost.topicObj = topic;
newPost.save().then(post => res.json(post));
})
.catch(err => {
res.send(err);
});
//how do i save this topic record I find and push an id into.
});
I had model Product, he was added without problem to db "products"
router.post('/create', function (req, res, next) {
console.log(req.body);
var newProduct = {
title: req.body.name,
price: req.body.price,
description: req.body.description,
quantity: req.body.quantity,
// category: req.body.category
}
var product = new Product(newProduct);
product.save(function (err, product) {
if (err) {
res.status(404).json({
message: 'Can not create this product'
})
} else {
console.log('added');
res.send(product);
}
});
});
Now i have model Category i was created http.post and all is working, but I have no idea where this things sended by post are save in database mongo
router.post('/create', function (req, res, next) {
var newCategory = {
name: req.body.name,
description: req.body.description
}
var category = new Category(newCategory);
category.save(function (err, category) {
if (err) {
res.status(404).json({
message: 'Can not create this category'
})
} else {
console.log('added');
res.send(category);
}
});
});
Can someone exaplain me??
As far as mongoose automatically transforms your model name to plurual forms, it should be - categories.
Update:
If you still want your singular naming, you can try something like this:
const Category = mongoose.model('Category ', Category Schema, 'Category ');