I am new to JS and I am trying to create a model with Mongoose but I get the following error: expected undefined to equal 'String' from the test system.
This is my code to create the model:
`
// CREATE MODEL: Album
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const model = mongoose.model;
const albumSchema = new Schema({
performer: {
type: String,
required: true
},
title: {
type: String,
required: true
},
cost: {
type: Number,
required: true,
},
});
const Album = model('Album', albumSchema)
// REMEMBER TO EXPORT YOUR MODEL:
module.exports = Album
`
This is the code of the tests:
const createdModels = Object.keys(mongoose.models);
describe('"Album" model', function () {
it("should be declared", function () {
expect(mongoose.models.Album).to.exist;
});
describe("should contain fields:", function () {
const albumModel = mongoose.models.Album;
const albumSchema = albumModel ? mongoose.models.Album.schema.obj : [];
it("performer: String", function () {
expect(albumSchema["performer"]).to.exist;
expect(albumSchema["performer"].name).to.equal("String");
});
it("title: String", function () {
expect(albumSchema["title"]).to.exist;
expect(albumSchema["title"].name).to.equal("String");
});
it("cost: Number", function () {
expect(albumSchema["cost"]).to.exist;
expect(albumSchema["cost"].name).to.equal("Number");
});
});
});
Related
I have two Mongoose model schemas as follows. The LabReport model contains an array of the referenced SoilLab model. There is a static method in the SoilLab model that I was using to select which fields to display when LabReport is retrieved.
//LabReport.js
var mongoose = require("mongoose");
var SoilLab = mongoose.model("SoilLab");
var LabReportSchema = new mongoose.Schema(
{
labFarm: { type: mongoose.Schema.Types.ObjectId, ref: "Farm" },
testName: { type: String },
soilLabs: [{ type: mongoose.Schema.Types.ObjectId, ref: "SoilLab" }],
},
{ timestamps: true, usePushEach: true }
);
LabReportSchema.methods.toLabToJSON = function () {
return {
labReport_id: this._id,
testName: this.testName,
soilLabs: this.soilLabs.SoilToLabJSON(),
};
};
mongoose.model("LabReport", LabReportSchema);
//SoilLab.js
var mongoose = require("mongoose");
var SoilLabSchema = new mongoose.Schema(
{
description: { type: String },
sampleDate: { type: Date },
source: { type: String },
},
{ timestamps: true, usePushEach: true }
);
SoilLabSchema.methods.SoilToLabJSON = function () {
return {
description: this.description,
sampleDate: this.sampleDate,
source: this.source,
};
};
mongoose.model("SoilLab", SoilLabSchema);
When I try to retrieve the LabReport, I get "this.soilLabs.SoilToLabJSON is not a function". This is how I'm trying to retrieve LabReport.
//labReports.js
...
return Promise.all([
LabReport.find()
.populate("soilLabs")
.exec(),
LabReport.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null,
]).then(function (results) {
var labReports = results[0];
var labReportsCount = results[1];
var user = results[2];
return res.json({
labReports: labReports.map(function (labReport) {
return labReport.toLabToJSON(user); //This cant find SoilToLabJSON
}),
If I remove the .SoilToLabJSON in LabReport.js and just call this.soilLabs, it works but outputs all of the soilLabs data which will become an issue when I have the model completed with more data. I have dug into statics vs methods a little and tried changing it to statics but it didn't work.
I get the soilLabs to populate but not sure why the .SoilToLabJSON method is inaccessible at this point. Do I need to find() or populate the soilLab differently? Is the method incorrect?
labReport.toLabToJSON is passing an array and that was causing the error for me. I simply edited the LabReport.js to the following to take the array and map it to SoilToLabJSON properly.
myTestSoilLabOutput = function (soilLabs) {
var test = soilLabs.map(function (soilLab) {
return soilLab.SoilToLabJSON();
});
return test;
Changed the LabReportSchema.methods.toLabToJSON to:
LabReportSchema.methods.toLabToJSON = function () {
return {
labReport_id: this._id,
testName: this.testName,
soilLabs: myTestSoilLabOutput(this.soilLabs),
};
};
The project is created with nodejs and mongoose. What I am trying to do is to update the existing model with addition data (which is a comment, in that case).
This is the model and its methods:
const bugSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: String,
required: true
},
time: {
type: String,
required: true
},
assignedTo: {
type: String,
required: true
},
assignedBy: {
type: String,
required: true
},
status: {
type: String,
required: true
},
priority: {
type: String,
required: true
},
comments: {
comment:[
{
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
}
]
}
});
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
const updatedComments = [...this.comments];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
The controller, which is passing the information from the form:
exports.postComment = (req,res,next) =>{
const bugId = req.body.bugID;
const name = req.session.user.fullName;
const content = req.body.content;
const prod = {name, content};
Bug.findById(bugId).then(bug =>{
return bug.addComment(prod);
})
.then(result =>{
console.log(result);
});
};
I am getting a following error:
(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable
(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable
The error indicate you're trying to iterable a type of data which does NOT has that capability.
You can check that printing the type:
console.log(typeof this.comments)
Or even, priting the whole object:
console.log(this.comments)
as you can see, in both cases you're getting an object, not a list (how you spect)
So you can do 2 things:
1- Iterable a list
this.comments is an object but into that object you have the list you want, so just use the list instead.
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
//const updatedComments = [...this.comments];
const updatedComments = [...this.comments.comment];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
Or you can modify your schema making the comments a list instead of an object
2- comments as list in schema
Define the comments attribute as a list
const bugSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
...
...,
comments:[
{
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
}
]
});
And then, try to iterable it as how you been doing
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
const updatedComments = [...this.comments];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
I am not sure but comments is an object and not an array so you can't push using [...this.comments] and I think it is the comment you want to push?
const updatedComments = [...this.comment];
updatedComments.push({
user : username,
content: content
});
this.comment = updatedComments;
From your schema comments is not an array. you are trying to spread an object into an array. const updatedComments = [...this.comments]; also push works on array.
try to modify your schema definitions by declaring the commentSchema outside the bugSchema.
const commentSchema = new Schema({
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
})
const bugSchema = new Schema({
comments: {
type: [commentSchema]
}
})
Bug.findByIdAndUpdate(bugId, {$push: {comments: newComment}})
Don't use findByIdAndUpdate Mongoose method, you better use save
it is written here https://mongoosejs.com/docs/tutorials/findoneandupdate.html
The findOneAndUpdate() function in Mongoose has a wide variety of use cases. You should use save() to update documents where possible, but there are some cases where you need to use findOneAndUpdate(). In this tutorial, you'll see how to use findOneAndUpdate(), and learn when you need to use it.
Below a router example
router.put('/items', (req, res) => {
if (!req.body._id || !req.body.title) {
return res.status(501).send({ message: 'Missing parameters, or incorrect parameters' });
}
return itemModel.findOne({ _id: req.body._id }, (err, item) => {
if (err) {
return res.status(500).send({
message: err
});
}
item.title = req.body.title; // <------------- You rewrite what was before stored on title attribute
return item.save((err, item) => { // <------------- You save it, this is not gonna create a new one, except if it doesn't exist already
if (err) {
return res.status(400).send({
message: 'Failed to update item'
});
} else {
return res.status(200).send({
message: 'Item update succesfully',
data: item
});
}
});
});
});
Here is my recipe.js file...
const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
const reviewSchema = require('../model/review');
let recipeSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
},
steps: {
type: String,
required: true,
},
ingredients: {
type: Array,
default: ['1', '2', '3', '4']
},
category: {
type: String,
required: true,
index: true
},
postedBy: {
type: String,
required: true,
},
reviewsOfRecipe: [reviewSchema],
numberOfRatings: {
type: Number,
default: 0
},
totalAddedRatings: {
type: Number,
default: 0
},
reviewAverage: {
type: Number,
default: 0
},
postersCreationDate: {
type: Number,
index: true
},
likedBy: {
type: Array
},
reviewedBy: {
type: Array
}
});
// Here is my static method
recipeSchema.methods.calculateAverage = function(){
let recipe = this;
if (recipe.numberOfRatings === 0 && recipe.totalAddedRatings === 0){
recipe.reviewAverage = 0;
}
else {
recipe.reviewAverage = recipe.totalAddedRatings / recipe.numberOfRatings
}
};
let Recipe = mongoose.model('Recipe', recipeSchema);
module.exports = Recipe;
In my router file, every time a user submits a review for a recipe, the fields numberOfRatings and totalAddedRatings get incremented. And after they get incremented, my static method calculateAverage should run and update the document.
Here is what it looks like in my code:
Recipe.findOneAndUpdate({_id: recipe._id, postersCreationDate: recipe.postersCreationDate},{$inc: {numberOfRatings: 1, totalAddedRatings: reviewScore}}, {returnNewDocument: true}).then((recipe) => {
recipe.calculateAverage();
});
However, every time a user submits a review, although numberOfRatings and numberOfRatings get incremented accordingly, reviewAverage does not.
I am thinking about setting reviewAverage as a virtual field instead; but I am worried that doing so would make it harder and inefficient to sort the recipes by the highest and lowest review averages.
first some things about your findOneAndUpdate can change. Id should be sufficient to find by and 'returnNewDocument' is not an option. In mongoose it's just 'new'
Recipe.findOneAndUpdate({_id: recipe._id},{$inc: {numberOfRatings: 1, totalAddedRatings: reviewScore}}, {new: true}).then((recipe) => {
recipe.calculateAverage();
});
The problem is that you aren't saving the average to the recipe.
recipeSchema.methods.calculateAverage = function(callback) {
let recipe = this;
if (recipe.numberOfRatings === 0 && recipe.totalAddedRatings === 0) {
recipe.reviewAverage = 0;
}
else {
recipe.reviewAverage = recipe.totalAddedRatings / recipe.numberOfRatings
}
recipe.save(callback);
};
I have document with the following structure on MongoDb,
I am using Mongoose version ^4.8.1 with my node application. I have created 3 schema models for the above document which are as follows,
Event.js
var mongoose = require('mongoose');
var eventSchema = new mongoose.Schema({
description: {
type: String
},
end_time: {
type: Date
},
start_time: {
type: Date
},
name: {
type: String
},
place: {
type: mongoose.Schema.Types.ObjectId,
ref: 'place'
}
});
eventSchema.index({name: 'text'},{'place.location.country':"text"});
var Event = mongoose.model('events', eventSchema);
module.exports= Event;
Place.js
var mongoose = require('mongoose');
var placeSchema = new mongoose.Schema({
name: {
type: String
},
location: {
type: mongoose.Schema.Types.ObjectId,
ref: 'location'
}
});
var Place = mongoose.model('place', placeSchema);
module.exports= Place;
Location.js
var mongoose = require('mongoose');
var locationSchema = new mongoose.Schema({
city: {
type: String
},
latitude: {
type: String
},
country: {
type: String
},
located_in: {
type: String
},
state: {
type: String
},
street: {
type: String
},
zip: {
type: String
},
});
var Location = mongoose.model('location', locationSchema);
module.exports= Location;
Common handler to access /query database,
dbHandler.js
querandpoplulate : function(model,condition,options)
{
return new Promise(function(resolve, reject) {
options = options||{};
console.log("model is" + model);
model.find({}).populate('place').populate('location').exec(function(error, data) {
if (error)
console.log(error);
reject(error);
console.log(data);
resolve(data);
})
})
}
Here is how i query,
dbHelper.querandpoplulate(mongoose.model('events'), {$text: {$search: searchString},'place.location.country': countryString},function(error,data){
callback(data);
});
Question: it does not return the result set with the place and location , it returns null in place field.
It looks to me like your documents are saved as embedded documents, but not as referenced documents.
To fetch such documents, you don't need to do any population. Simple find query should work for you.
Try this:
model.find({}).exec(function(error, data) {
if (error)
console.log(error);
reject(error);
console.log(data);
resolve(data);
})
As you are not saving the data in the mongoDB but only retrieving it. you need to define the schema that matches with the document structure.
As discussed with you, i think you need to change the Schema, and combine all 3 schemas in one file (Event.js).
var mongoose = require('mongoose');
var locationSchema = new mongoose.Schema({
city: {
type: String
},
//add other fields here
});
var placeSchema = new mongoose.Schema({
name: {
type: String
},
location: locationSchema
});
var eventSchema = new mongoose.Schema({
description: {
type: String
},
//add other fields here too
place: placeSchema
});
eventSchema.index({name: 'text'},{'place.location.country':"text"});
var Event = mongoose.model('events', eventSchema);
module.exports= Event;
I have experience in writing statics functions in moongose like
var mongoose =require('mongoose');
var Schema = mongoose.Schema;
var adminSchema = new Schema({
fullname : String,
number : Number,
email: String,
auth : {
username: String,
password : String,
salt: String
}
});
adminSchema.statics.usernameInUse = function (username, callback) {
this.findOne({ 'auth.username' : username }, function (err, doc) {
if (err) callback(err);
else if (doc) callback(null, true);
else callback(null, false);
});
};
here usernameInUse is the function I wana write but using sequelize for mysql database
my model
/*
This module is attendant_user table model.
It will store attendants accounts details.
*/
"use strict";
module.exports = function(sequelize, DataTypes) {
var AttendantUser = sequelize.define('AttendantUser', {
username : {
type : DataTypes.STRING,
allowNull : false,
validate : {
isAlpha : true
}
},{
freezeTableName : true,
paranoid : true
});
return AttendantUser;
};
How to add statics function here..??
Well, you can easily use Expansion of models
var User = sequelize.define('user', { firstname: Sequelize.STRING });
// Adding a class level method
User.classLevelMethod = function() {
return 'foo';
};
// Adding an instance level method
User.prototype.instanceLevelMethod = function() {
return 'bar';
};
OR in some cases you may use getter and setter on your models. See the docs:
A) Defining as part of a property:
var Employee = sequelize.define('employee', {
name: {
type : Sequelize.STRING,
allowNull: false,
get : function() {
var title = this.getDataValue('title');
// 'this' allows you to access attributes of the instance
return this.getDataValue('name') + ' (' + title + ')';
},
},
title: {
type : Sequelize.STRING,
allowNull: false,
set : function(val) {
this.setDataValue('title', val.toUpperCase());
}
}
});
Employee
.create({ name: 'John Doe', title: 'senior engineer' })
.then(function(employee) {
console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
console.log(employee.get('title')); // SENIOR ENGINEER
})
B) Defining as part of the model:
var Foo = sequelize.define('foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
getterMethods : {
fullName : function() { return this.firstname + ' ' + this.lastname }
},
setterMethods : {
fullName : function(value) {
var names = value.split(' ');
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
},
}
});
Hope it helps.
AttendantUser.usernameInUse = function (username, callback) {
...
};
return AttendantUser;