I set up my schema like so:
var videoSchema = new Schema({
title: String,
url: String, //Link to the video
rating: { type: Number, default: 0},
description: String //a paragraph or two to go along with the video
});
var tutorialPageSchema = new Schema({
title: String, //IE Peeking, Clutching, etc.
tutorials: [videoSchema]
});
var categorySchema = new Schema({
title: String, //intermediate, beginner, config, map knowledge, etc.
pages: [tutorialPageSchema]
});
exports.Video = mongoose.model('video', videoSchema);
exports.TutorialPage = mongoose.model('tutorialPage', tutorialPageSchema);
exports.Category = mongoose.model('category', categorySchema);
Add the document like so:
var newPage = new models.TutorialPage({
title: req.query.page.title,
tutorials: []
});
parentCategory.pages.push(newPage);
In return, it gives me a nice "TypeError: Cannot call method 'push' of undefined
"
Other times the question was asked, people didn't load the schemas in the correct order or conflated the Model with the Schema when setting the schema up, but that doesn't seem to be my problem. What gives?
Related
I am trying to create a mongoose schema that is an array of Maps that are String -> String:
var daySchema = new mongoose.Schema({
schedule: {
type: [Map],
of: String
}
});
This is what I have, but it's giving me a validation error.
How about creating a separate schema for the maps and then use that schema in an array:
var Schedule = new mongoose.Schema({
type: Map,
of: String
});
var daySchema = new mongoose.Schema({
type: [Schedule]
});
As shown in the array examples.
You could do this:
var daySchema = new mongoose.Schema({
schedule: {
type: [{type: Map, of: String}],
}
});
I'm trying to return a result from my mongoose find operation. I know a lot of question have already been asked for this but i think this is different. Here's my user :
var UserSchema = new mongoose.Schema({
variable: {type: mongoose.Schema.ObjectId, ref: 'Variable'}
});
My user have a method to retrieve his variable. Here's the problem.
UserSchema.methods.getVariable = function() {
//TODO ?
}
I don't know how to populate my field and then return the result of the populate...
I think you can just use populate
var UserSchema = new mongoose.Schema({
variable: {type: mongoose.Schema.ObjectId, ref: 'Variable'}
});
UserSchema.
findOne({your:"query"}).
populate('variable').
exec().
then(
user=>console.log("user is:",user)
);
I try to fill a document in MongoDB with NodeJS, consequently I created a Schema and a post req.
var gameSchema = new Schema({
title: String,
developer: {
name: String,
email: String
},
isBroadcasted: Boolean
});
So I want to populate this schema thanks to a req.
router.post('/android', auth, function(req, res){
// Create a new instance of the Game model
var game = new Game();
game.title = req.body.title;
game.developer.name = req.body.developer.name;
game.developer.email = req.body.developer.email;
But, when I run it there is an error message "TypeError: Cannot read property 'name' of undefined" but I don't understand why because developer.name exists.
I guess the error is not referring to game.developer.name but to req.body.developer.name.
Try changing your line to
game.developer.name = req.body['developer.name']
as your parameter developer.name is parsed as string, not as nested object.
I was just wondering why something like this isn't allowed in mongoose schema definitions:
var NameSchema = new mongoose.Schema({
first: {type: String, trim: true },
last: {type: String, trim: true }
});
var UserSchema = new mongoose.Schema({
name: NameSchema, // this line causes an error
age: {type: Number}
});
It seems like a design decision, I was just wondering if I could get an explanation as to why it isn't supported
Thanks!
You can nest a schema using this method:
name: [{ some: "props" } ]
or
name: [NameSchema]
The problem with giving directly the schema definition (without using "type: ...") is that Mongoose can't make the difference between the option object and the schema object. Mongoose will think that NameSchema is actually an option object (containing options such as the type, trim...).
How can I add a schema to another schema? This doesn't seem to be valid:
var UserSchema = new Schema({
name : String,
app_key : String,
app_secret : String
})
var TaskSchema = new Schema({
name : String,
lastPerformed : Date,
folder : String,
user : UserSchema
})
I checked the website and it shows how to declare it for an array but not for single.
Thanks
There are a few ways to do this. The simplest is just this:
var TaskSchema = new Schema({
name : String,
lastPerformed : Date,
folder : String,
user : Schema.ObjectId
});
Then you just have to make sure your app is writing that id and using it in queries to fetch "related" data as necessary.
This is fine when searching tasks by user id, but more cumbersome when querying the user by task id:
// Get tasks with user id
Task.find({user: user_id}, function(err, tasks) {...});
// Get user from task id
Task.findById(id, function(err, task) {
User.findById(task.user, function(err, user) {
// do stuff with user
}
}
Another way is to take advantage of Mongoose's populate feature to simplify your queries. To get this, you could do the following:
var UserSchema = new Schema({
name : String,
app_key : String,
app_secret : String,
tasks : [{type: Schema.ObjectId, ref: 'Task'}] // assuming you name your model Task
});
var TaskSchema = new Schema({
name : String,
lastPerformed : Date,
folder : String,
user : {type: Schema.ObjectId, ref: 'User'} // assuming you name your model User
});
With this, your query for all users, including arrays of their tasks might be:
User.find({}).populate('tasks').run(function(err, users) {
// do something
});
Of course, this means maintaining the ids in both places. If that bothers you, it may be best to stick to the first method and just get used to writing more complex (but still simple enough) queries.
As of version 4.2.0, mongoose supports single subdocuments.
From the docs:
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
// Array of subdocuments
children: [childSchema],
// Single nested subdocuments. Caveat: single nested subdocs only work
// in mongoose >= 4.2.0
child: childSchema
});
What about this simple solution?
var TaskSchema = new Schema({
name : String,
lastPerformed : Date,
folder : String,
user : {
name : String,
app_key : String,
app_secret : String
}
})