I'm developing a simple CRUD project with Express, using Handlebars and connecting to a Mongo database. I have some trouble when trying to print the results of a query in a template.
I already have my DB populated, and my model is defined as follows:
let movieSchema = new Schema({
director: {
type: String,
required: true
},
title: String,
}, {
timestamps : true
});
module.exports = mongoose.model("Movie", movieSchema);
Documents in the database have more fields than the model defined in my code (year, genre, rate...).
I have a root where a template is rendered, with a list of all of the retrieved elements of the collection movies. When the route handler is defined as follows, it works perfectly, and when sending the response, the movies array is correctly filled with all of the movies retrieved from the database.
Movie.find()
.then(movies => {
console.log("movies: ", movies);
res.send({
title: "Movie list",
movies
});
})
.catch(err => {
res.send(err);
}
But if I convert the res.send to a res.render, in order to show all data in the corresponding view, I have only access from the template to the fields that are defined in the model:
Movie.find()
.then(movies => {
console.log("movies: ", movies);
//changed res.send to res.render
res.render("films", {
title: "Movie list",
movies
});
})
.catch(err => {
res.send(err);
}
If I create a deep copy of movies, then res.render allows the template to get all the parameters of the movies array:
Movie.find()
.then(movies => {
console.log("movies: ", movies);
//deep copy of movies:
let moviesCopy = JSON.parse(JSON.stringify(movies));
res.render("films", {
title: "Movie list",
movies: moviesCopy
});
})
.catch(err => {
res.send(err);
}
It also works fine if I define the Schema in strict mode set to false:
let movieSchema = new Schema({
director: {
type: String,
required: true
},
title: String,
}, {
timestamps : true,
//strict mode set to false:
strict: false
});
module.exports = mongoose.model("Movie", movieSchema);
I cannot understand why I can perfectly see all the fields of the documents from the database with find() when using res.send, but when I use res.render I can only see the fields defined in the schema.
Any idea?
Related
I am at my wits end with something that is seemingly straightforward:
I need to be able to push new gifts into the Events Array under the specific user. Because each event will have numerous gifts added, I want to keep them all under the user, as they are the one creating the event, and the gifts will live inside of their event where they belong.
The PROBLEM is: when I use the mongoose method 'findByIdAndUpdate', I can only find the main user, and from there, push an event to the events array. What I NEED to be able to do: push gifts to a specific event under that user. I am using mongoose Subdocuments. See my schema below and how I have a subdocument schema (EventSchema) inside of the main user schema, and a subdocument (gift) schema inside the event schema.
SCHEMA:
const Schema = mongoose.Schema;
let giftArr = new Schema({
giftname: String,
giftlink: String,
claimed: Boolean,
claimee: String
})
let eventSchema = new Schema({
eventname: String,
eventowner: String,
date: {
type: Date,
default: Date.now
},
attendees: [
{
attendeename: String
}
],
gift: [giftArr]
})
let userSchema = new Schema({
username: String,
email: { type: String, required: false },
events: [eventSchema]
});
Here are my controllers for my POST & GET routes:
export const insertEventsById = ((req, res) => {
const update = { $push: { events: req.body } }
const id = req.params.userID
Gift.findByIdAndUpdate(id, update, (err, data) => {
if (err) {
console.log(err);
} else {
res.json(data)
console.log(data);
}
})
})
export const getUserById = (req, res) => {
Gift.findById(req.params.userID, (err, user) => {
if(err){
res.send(err)
}
res.json(user)
})
}
To further illustrate, here is my postman GET request for a USER. I can push to the 'events' array (red arrow) as my findByIdAndUpdate method shows above, but when I attempt to go one nested level deeper, into the gift array (green arrow), I cannot find any documentation on that.
I been up and down the mongoose subdocuments and queries pages, and I cannot find a method that will pull specifically the '_id' of the particular event I need. I have even tried the methods on the embedded schemas to specifically look for _id's that way.
Can someone point out where I am going wrong here? Thanks in advance...as always fellow Stacks.
I'm building a movie database with MongoDB, node.js, and express. I have two routes currently, one that renders a page that displays all of the movies in the database, and another that displays information for an individual movie. The problem is when rendering the page for each individual movie with ejs, I am not able to parse the object that is passed, which holds things like the title, the year, and a few arrays of images.
When rendering the all movies page, I am able to parse the object and display it with ejs. So I am not sure what the difference between the two routes is.
Schema for Movie
const movieSchema = new mongoose.Schema({
name: String,
date: String,
production: String,
cast: String,
remarks: String,
lobbyCards: Array,
filmStills: [
{
url: String,
caption: String
}
],
behindStills: [
{
url: String,
caption: String
}
],
advertising: [
{
url: String,
caption: String
}
]
});
Here are the two routes:
All Movies
app.get('/movies', (req, res) => {
movie.find({}, (err, movies) => {
if (err) {
console.log(err);
} else {
res.render('movies', { movies: movies });
// console.log(movies);
}
});
});
Individual Movie
app.get('/movies/:name', (req, res) => {
movie.find({ name: req.params.name }, (err, movieData) => {
if (err) {
console.log(err);
} else {
res.render('show', { movieData: movieData });
}
});
});
If I console.log(movieData) it is logged as an array.
All Films Ejs file
Individual Film Ejs file
This is what renders from the All films page
All films
This is what renders from the Individual Film Page
Individual film
If you want to get a single document from the db, you probably want to use:
movie.findOne({ name: req.params.name }, (err, movieData) => { ... }
With .find() an array is returned even when only one document matches the query which is why the movie object cannot be displayed in your ejs.
i have this Schema for a simple twitter app
const userSchema = new Schema ({
loginInfo: {
username: String,
email: String,
password: String
},
tweets: [{
content: String,
likes: Number,
comments: [{
owner: String,
content: String,
likes: Number
}]
}],
followers: [String],
following: [String]
})
and i want to make endpoint that return only the tweet that has the same _id that has been given as a params on the URL ..
I made that solution below and its working correctly but i believe there is a much better solution than this ..
const handleTweet = (User) => (req,res) => {
const { id } = req.params;
let theTweet = [];
User.findOne({ "tweets._id": id})
.then(user => {
user.tweets.forEach(tweet => {
if(tweet._id.toString() === id)
return theTweet.push(tweet)
})
res.json(theTweet)
})
.catch(err => res.json(err))
}
module.exports = handleTweet;
One more question : Is it better to make nested schemas like this or making a different models for each schema (in this case schema for User and another one for Tweets) ?
You should make the tweets into a different collection since you are querying based on that, and then you can use autopopulate when you need it.
Also instead of the foreach you could use Array.prototype.find
Hope this helps!
You can use the $push & findOneAndUpdate methods from mongoose. You can modify your example to be like this:
User.findOneAndUpdate(id, { $push: { tweets: req.body.tweet } }, {new: true})
.then((record) => {
res.status(200).send(record);
})
.catch(() => {
throw new Error("An error occurred");
});
Notice the {new: true} option, it makes the findOneAndUpdate method to return the record with the edit.
For your second question, it's recommended to split the modals to make your code more readable, maintainable and easy to understand.
What im doing:
When I call getData() the backend server .find() all my data.
My documents:
My test document has an _id a name and stuff fields. The stuff field contains the _id to the data document.
My data document has an _id and a age field
My goal:
When I send the data to the frontend I donĀ“t want the stuff field to appear with the _id, I want it to appear with the age field from the correspondingdata.
What I have:
router.route('/data').get((req, res) => {
Test.find((err, aval) => {
if (err)
console.log(err);
else{
var result = [];
aval.forEach(e => {
var age;
// Get the age, only 1
Data.findById(e.stuff, 'age', function (err, a) {
age = a.age;
});
result.push({name: e.name, age: age});
});
res.json(result);
}
});
});
I find all the test documents then, for each one of them, I find the age and put the result in the array. Finaly I send the result array.
My problem:
The age field on my result array is always undefined, why? Any solutions?
UPDATE 1 - The schemas
The test schema
var TestSchema = new Schema(
{
stuff: {type: Schema.Types.ObjectId, ref: 'Data', required: true},
name: {type: String, required: true}
}
);
The data schema
var DataSchema = new Schema(
{
age: {type: Number, required: true}
}
);
router.route('/data').get((req, res) => {
Test.find({})
.populate('stuff')
.exec((err, aval) => {
if (err) console.log(err);
res.json(aval);
});
});
Mongoose model has a populate property that uses the value in the model attribute definition to get data matching the _id from another model.
It's a scop problem with your code try this out :
Data.findById(e.stuff, 'age', function (err, a) {
result.push({name: e.name, age: a.age});
});
But as a better solution think to use the Aggregation Framework
Users are able to post items which other users can request. So, a user creates one item and many users can request it. So, I thought the best way would be to put an array of users into the product schema for who has requested it. And for now I just want to store that users ID and first name. Here is the schema:
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: {
type: String,
required: true
},
category: {
type: String,
required: true
},
description: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
requests: [
{
userId: {type: Object},
firstName: {type: String}
}
],
});
module.exports = mongoose.model('Product', productSchema);
In my controller I am first finding the item and then calling save().
exports.postRequest = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
const firstName = req.body.firstName;
const data = {userId: userId, firstName: firstName};
Product.findById(productId).then(product => {
product.requests.push(data);
return product
.save()
.then(() => {
res.status(200).json({ message: "success" });
})
.catch(err => {
res.status(500).json({message: 'Something went wrong'});
});
});
};
Firstly, is it okay to do it like this? I found a few posts about this but they don't find and call save, they use findByIdAndUpdate() and $push. Is it 'wrong' to do it how I have done it? This is the second way I tried it and I get the same result in the database:
exports.postRequest = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
const firstName = req.body.firstName;
const data = {userId: userId, firstName: firstName};
Product.findByIdAndUpdate(productId, {
$push: {requests: data}
})
.then(() => {
console.log('succes');
})
.catch(err => {
console.log(err);
})
};
And secondly, if you look at the screen shot is the data in the correct format and structure? I don't know why there is _id in there as well instead of just the user ID and first name.
Normally, Developers will save only the reference of other collection(users) in the collection(product). In addition, you had saved username also. Thats fine.
Both of your methods work. But, second method has been added in MongoDB exactly for your specific need. So, no harm in using second method.
There is nothing wrong doing it the way you have done it. using save after querying gives you the chance to validate some things in the data as well for one.
and you can add additional fields as well (if included in the Schema). for an example if your current json return doesn't have a field called last_name then you can add that and save the doc as well so that's a benefit..
When using findById() you don't actually have the power to make a change other than what you program it to do
One thing I noticed.. In your Schema, after you compile it using mongoose.modal()
export the compiled model so that you can use it everywhere it's required using import. like this..
const Product = module.exports = mongoose.model('Product', productSchema);