Mongoose schema with object - javascript

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.

Related

Schema hasn't been registered for model in Schema but not others from the same source

I am trying to populate a node express route with information from Schemas, and I keep getting this error. What I cannot understand is that I am referencing three different fields in the same exact Schema and for some reason, I am only getting this error for one of those fields.
This is my route function where I am getting "MissingSchemaError: Schema hasn't been registered for model "completed_by_user""
// Schemas
const Transaction = require ("../models/transaction");
User = require ("../models/user");
Ticket = require ("../models/ticket");
Job = require ("../models/job");
Client = require ("../models/client");
// Functions
let numberWithCommas = require("../functions/numberWithCommas");
module.exports = function(app) {
// =======================Tickets
// index
app.get("/tickets", function(req, res){
Ticket.find({}).populate("created_by", "assigned_user", "completed_by_user").exec(function(err, tickets){ //This is where it happens
if(err){
console.log(err)
} else {
res.render("tickets", {tickets: tickets});
}
});
});
And this is the Ticket Schema itself:
const Transaction = require ("./transaction");
User = require ("./user");
Ticket = require ("./ticket");
Job = require ("./job");
Client = require ("./client");
// =======================Ticket Schema
var ticketSchema = new mongoose.Schema({
ticket_name: String,
description: String,
created_by: [{type: mongoose.Schema.Types.ObjectID, ref: "User"}],
assigned_user: [{type: mongoose.Schema.Types.ObjectID, ref: "User"}],
completed_by_user: [{type: mongoose.Schema.Types.ObjectID, ref: "User"}],
due_date: {type: Date},
completed_date: {type: Date},
completed_description: String,
date_added: {type: Date, default: Date.now}
});
module.exports = mongoose.model("Ticket", ticketSchema);
I am not getting this error for "created_by" or for "assigned_user" but I am getting it for "completed_by_user." I don't understand why this would be since they are all populated in the same Schema. This is not the only occurrence of this type of issue I am having, but I am sure it is for the same reason. I even tried changing the order I require the schemas and that has not helped either. Is there something obvious I am missing? Thanks.
.populate(["created_by", "assigned_user", "completed_by_user"])
Try this because .populate function takes only one argument by putting it into array it takes multiple

Update Array attribute using Mongoose

I am working on a MEAN stack application in which i defined a model using following schema:
var mappingSchema = new mongoose.Schema({
MainName: String,
Addr: String,
Mapping1: [Schema1],
Mappings2: [Schema2]
},
{collection : 'Mappings'}
);
I am displaying all this data on UI and Mapping1 & Mapping2 are displayed in the 2 tables where I can edit the values. What I am trying to do is once I update the values in table I should update them in database. I wrote put() api where I am getting these two updated mappings in the form of object but not able to update it in database. I tried using findAndModify() & findOneAndUpdate() but failed.
Here are the Schema1 & Schema2:
const Schema1 = new mongoose.Schema({
Name: String,
Variable: String
});
const Schema2 = new mongoose.Schema({
SName: String,
Provider: String
});
and my put api:
.put(function(req, res){
var query = {MainName: req.params.mainname};
var mapp = {Mapping1: req.params.mapping1, Mapping2: req.params.mapping2};
Mappings.findOneAndUpdate(
query,
{$set:mapp},
{},
function(err, object) {
if (err){
console.warn(err.message); // returns error if no matching object found
}else{
console.log(object);
}
});
});
Please suggest the best to way update those two arrays.
UPDATE :
I tried this
var mapp = {'Mapping2': req.params.mapping2};
Mappings.update( query ,
mapp ,
{ },
function (err, object) {
if (err || !object) {
console.log(err);
res.json({
status: 400,
message: "Unable to update" + err
});
} else {
return res.json(object);
}
});
what I got is
My array with size 3 is saved as String in Mapping2 array.
Please help. Stuck badly. :(
From Mongoose's documentation I believe there's no need to use $set. Just pass an object with the properties to update :
Mappings.findOneAndUpdate(
query,
mapp, // Object containing the keys to update
function(err, object) {...}
);

JSON object architecture looks different when I pass it to the client side

Here is my Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var messageSchema = new Schema({
requestNumber: String,
requestedDateTime: String,
reasons: String,
state: String,
hospital: String,
phone: String,
status: {type: String, default: 'Pending'},
latestUpdate: Date,
createdAt: {type: Date, default: Date.now}
});
module.exports = mongoose.model('Requests', messageSchema);
Below I am returning the collection with three components in it
ipcMain.on('load-requests', function(event) {
hosSchemaModel.find(function(err, hosSchema) {
if (err) {
console.log('inside error') // return res.send(err);
} else {
event.sender.send('requests-results', hosSchema) // this line of code passes hosSchema to the client side
console.log(hosSchema[0].state) //prints the state attribute of the first component in the collection without any errors.
}
});
});
When I try to console.log(hosSchema) in the server, I get the following printed to the terminal:
and I could successfully access the properties such as status of the first component in the collection by referring to its index hosSchema[0].status.
Below I am trying to print hosSchema to the console (in the front-end)
ipcRenderer.on('requests-results', (event, hosSchema) => {
console.log(hosSchema)
})
I get the result different from what they were looking in the terminal. below is the picture
and hosSchema[0].status returns undefined.
My questions are:
1) why hosSchema[0].status doesn't work in the front-end?
2) what is the correct way to access the properties in the client-side?
All you have to do in the front end is to use hosSchema[0]._doc.status instead of hosSchema[0].status

Mongoose: Cannot call method 'push' of undefined, on nested Schema

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?

Update/Put error save in Express and Mongoose

I am beginner in Express. I have the following code in my router/controller for update a model. In one hand I don't want to modify the date of "create_date" parameter, and on the second hand this code returns me a error.
updateFood = function(req, res){
Food.findById(req.params.id, function(err, food){
food.food_name = req.body.food_name;
food.description = req.body.description;
food.image = req.body.image;
food.create_date = Date.now();
food.category = req.body.category;
Food.save(function(err){
if (!err){
console.log("updated!");
} else {
console.log(err);
}
});
res.send(food);
});
};
Here is my schema:
var food = new Schema({
food_name: {type: String, unique: true},
description: String,
image: String,
create_date: {type: Date, default: Date.now()},
category: {
type: String,
cats: ['Meat', 'Fish', 'Vegetables']
}
});
module.exports = mongoose.model('Food', food);
When I try to update a food with Postman with PUT. The console returns me the following response:
Food.save(function(err){
^
TypeError: Object function model(doc, fields, skipId) {
if (!(this instanceof model))
return new model(doc, fields, skipId);
Model.call(this, doc, fields, skipId);
} has no method 'save'
What can I do? Anyone knows where is my mistake? Thanks.
I believe you meant food.save(..); instead of Food.save(..);, but if all you're doing is updating the model, you could use findByIdAndUpdate() instead.

Categories

Resources