SantiagoGlz SantiagoGlz - 6 months ago 35
Node.js Question

TypeError object is not a function

I'm developing an application in node.js with MongoDB
I have to files:
product.js and displaycost.js

this is product .js:

var mongoose = require('mongoose');
var Category = require('./category');

var productSchema = {
name:{type: String, require: true},
//Pictures mus start with "http://"
pictures:[{type:String, match: /^http:\/\//i}],
price:{
amount:{type: Number, required: true},
//ONly 3 supported currencies for now
currency:{
type: String,
enum:['USD','EUR','GBP'],
required: true
}
},
category: Category.categorySchema
};
var schema = new mongoose.Schema(productSchema);

var currencySymbols ={
'USD': '$',
'EUR':'€',
'GBP':'£'
};

/*
*
*/
schema.virtual('displayPrice').get(function(){
return currencySymbols[this.price.currency] +
'' + this.price.amount;
});

schema.set('toObject', {virtuals:true});
schema.set('toJSON', {virtuals:true});

module.exports = schema;


What I need is create a record with "productSchema"
I tried with this:

var Product = require('./product.js');

var p = new Product({
name: 'test',
price:{
amount : 5,
currency: 'USD'
},
category: {
name: 'test'
}
});

console.log(p.displayPrice); // "$5"

p.price.amount = 20;
console.log(p.displayPrice); //" $20"

//{... "displayPrice: "$20",...}
console.log(JSON.stringify(p));

var obj = p.toObject();


But when I run the displaycost.js throw me an error at the word "new"
and writes "TypeError: object is not a function"

I don't know why is happening that. Thank you.

Answer

you missing export mongoose model with model name.

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    Category = require('./category');

var productSchema = new Schema({
    name: {type: String, require: true},
    pictures: [{type: String, match: /^http:\/\//i}],
    price: {
        amount: {type: Number, required: true},
        currency: {
            type: String,
            enum: ['USD', 'EUR', 'GBP'],
            required: true
        }
    },
    category: Category
});

var currencySymbols = {
    'USD': '$',
    'EUR': '€',
    'GBP': '£'
};

productSchema.virtual('displayPrice').get(function () {
    return currencySymbols[this.price.currency] +
        '' + this.price.amount;
});

productSchema.set('toObject', {virtuals: true});
productSchema.set('toJSON', {virtuals: true});

module.exports = mongoose.model('Product', productSchema);