How to include schema of other model in nodejs? - node.js

I have 2 schema products and orders as shown below:
products.js
var mongoose = require('mongoose');
const productsSchema = mongoose.Schema({
prod_name : {
type: String,
required: true
},
qty : {
type: Number,
required: true
},
price : {
type: Number,
require: true
}
});
mongoose.model('Products', productsSchema);
orders.js
const mongoose = require('mongoose');
const ProductsModel = mongoose.model('Products');
const OrdersSchema = mongoose.Schema({
order_date : {
type: Date,
required: true
},
sum : {
type: Number,
required: true
},
products: [ProductsModel]
});
const Orders = module.exports = mongoose.model('Orders', OrdersSchema);
app.js where am referencing the files
var express = require('express');
var mongoose = require('mongoose');
var app = express();
const contact = require('./routes/contacts');
const product = require('./routes/products');
const order = require('./routes/orders');
mongoose.connect('mongodb://localhost:27017/contactlist')
const port = 3000;
app.use('/contacts', contact);
app.use('/products', product);
app.use('/orders', order);
app.listen(port, () => {
console.log('Server started at port ' + port);
})
In above orders.js am trying to include products schema and its giving below error
MissingSchemaError: Schema hasn't been registered for model "Products".
I want to store array of products in same orders schema.
Where am i doing wrong?

To have a reusable mongoose model you should export the schema as a model
like the following code:
const mongoose = require('mongoose');
const productsSchema = mongoose.Schema({
prod_name : {
type: String,
required: true
},
qty : {
type: Number,
required: true
},
price : {
type: Number,
require: true
}
});
module.exports = mongoose.model('Products', productsSchema);

The problem is probably that you forgot to use new which creates a new Schema.
Try changing :
const productsSchema = mongoose.Schema
To :
const productsSchema = new mongoose.Schema
In orders.js you will be able to get the schema like this :
mongoose.model('Products').schema

Related

mongoose schema inner join not getting result in my case

i am following many example of mongoose for inner join with schema but not getting response my other tables.
my question is what is missing in my code please help me this.
i want getting result of class and subjects also.
exports.classSubjectList = async (req, res, next) => {
const obj = await ClassSubject.find().populate('classmodel').exec();
res.status(200).json({
success: true,
response: obj
});
};
//ClassSubjectModel
const mongoose = require('mongoose');
mongoose.Promise = global.Promise
const Schema = mongoose.Schema
const classModel = require('../class/classModel');
const subjectModel = require('../subject/subjectModel');
var classsubject = new Schema({
ClassId: String,
SubjectId : String,
IsShow: { type: Boolean, default : true},
classmodel: { type: mongoose.Schema.Types.ObjectId, ref: classModel },
subjectmodel: { type: mongoose.Schema.Types.ObjectId, ref: subjectModel },
});
//Class Model
const mongoose = require('mongoose');
mongoose.Promise = global.Promise
const Schema = mongoose.Schema
var classinfo = new Schema({
ClassName: String,
IsShow: { type: Boolean, default : true},
});
module.exports = mongoose.model('classinfo', classinfo);
//SUBJECT Model
const mongoose = require('mongoose');
mongoose.Promise = global.Promise
const Schema = mongoose.Schema
var subject = new Schema({
SubjectName: String,
IsShow: Boolean,
});
module.exports = mongoose.model('subject', subject);
result
[
{
"IsShow": true,
"_id": "5e1efc0f354849246c472cfe",
"SubjectId": "5e1da60bf52acb30b87e92c4",
"ClassId": "5e1ec13ed777bf28d01e2481",
"__v": 0
}]
You have to use model name instead of using file/object name in populate like as bellow.
exports.classSubjectList = async (req, res, next) => {
const obj = await ClassSubject.find().populate('classinfo').exec();
res.status(200).json({
success: true,
response: obj
});
};
//ClassSubjectModel
const mongoose = require('mongoose');
mongoose.Promise = global.Promise
const Schema = mongoose.Schema
const classModel = require('../class/classModel');
const subjectModel = require('../subject/subjectModel');
var classsubject = new Schema({
ClassId: String,
SubjectId : String,
IsShow: { type: Boolean, default : true},
classmodel: { type: mongoose.Schema.Types.ObjectId, ref: classinfo },
subjectmodel: { type: mongoose.Schema.Types.ObjectId, ref: subjectModel },
});

Invalid schema configuration: `model` is not a valid type within the array `characters`

I'm trying to create a schema subdocument but am getting the error listed above,
The schemas in question look like this
Schema casuing issues
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const CharacterSchema = new Schema();
CharacterSchema.add({
name: {
type: String,
required: true
},
title: {
type: String
},
charcterClass: { // will be limited in form creation
type: String
},
level: {
type: Number
}
});
const Charcter = mongoose.model('User', CharacterSchema);
module.exports = Charcter;
Schema calling schema above
const mongoose = require ('mongoose');
const Schema = mongoose.Schema;
const {CharacterSchema} = require(__dirname +'/CharacterModel.js');
const UserSchema = new Schema()
UserSchema.add({
name: {
type: String,
required: true
} ,
characters: [CharacterSchema]
});
const User = mongoose.model('Character', UserSchema);
module.exports = User;
Try to do the import like this way
const {CharacterSchema} = require(__dirname +'/CharacterModel.js').schema;
Adding the .schema at the end.
This post is related to your issue, you will see the explanation there.
Embedding schemas is giving error
UserSchema :
const mongoose = require ('mongoose');
const Schema = mongoose.Schema;
const CharacterSchema = new Schema({
name: {
type: String,
required: true
},
title: {
type: String
},
charcterClass: {
type: String
},
level: {
type: Number
}
});
const UserSchema = new Schema({
name: {
type: String,
required: true
} ,
characters:{
type:[CharacterSchema]
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;

Node.js API is not returning anything (no errors)

My API is not throwing any error ( as it is printing Listening on Port 3000 on the console ) but it isn't returning anything either. When I try testing it on postman, it says Could not get any response.
Can anyone help me with figuring out what the problem could be? The code is below.
PS: I have been referring this CRUD operations tutorial
This is my file structure:
server.js
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose');
const resortRoute = require('./routes/resort_routes');
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost/db', { useNewUrlParser: true }) //mongodb://127.0.0.1:27017
var db = mongoose.connection
db.on('error', console.error.bind(console, 'Mongodb connection error:'))
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use('/resort', resortRoute);
const port = process.env.PORT || 3000;
const server = app.listen(function(){
console.log('Listening on port ' + port);
});
Resort model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var childSchema = mongoose.Schema({
name : String,
price : Number
}, { _id : false });
let Resort = new Schema({
cover_image : {
type: String,
required: true
},
price: {
actual_price: { type: Number, required: true},
discount_price: {type: Number, required: true}
},
themes : { type: Array },
features : { type : Array },
food : [childSchema],
trip_type: { type : Array },
stay_package : [childSchema],
additional : [childSchema],
activities : [childSchema],
name : {
type: String,
required: true
},
excerpt : {
type: String,
},
description : {
type: String,
required: true
},
destinationId : { type: mongoose.Schema.Types.Mixed, ref: 'Destination', required: true },
itinerary : { type: mongoose.Schema.Types.Mixed },
maps : {
type : String,
// required: true
},
address : {
type : String,
// required: true
},
distance_from : {
location : String,
distance : Number,
}
},{
collection: 'resort'
});
module.exports = mongoose.model('Resort', Resort);
resort_routes.js
const express = require('express');
const app = express();
const resortRoutes = express.Router();
let Resort = require('../models/Resort');
resortRoutes.route('/create').post(function (req, res) {
console.log(req.body)
let resort = new Resort(req.body);
resort.save()
.then(resort => {
res.status(200).json({'resort': 'resort added'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
module.exports = resortRoutes;

I can't handle populate in mongoose

I think it's not populating categories couse when i try log 'category' in console i get
"ReferenceError: category is not defined". For me it is like in docs but as we see it's not. Is anyone can tell me what is wrong??
//model/Category.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CatSchema = new Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
}
});
mongoose.model("categories", CatSchema, "categories");
model/Story.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const StorySchema = new Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
category: {
type: Schema.Types.ObjectId,
ref: "categories"
}
});
mongoose.model("stories", StorySchema, "stories");
routes/stories.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Category = mongoose.model('categories');
const Story = mongoose.model('stories');
router.get('/add', (req, res) => {
Story.find()
.populate('category', 'title')
.then(stories => {
res.render('stories/add', {
stories: stories
});
});
});
Query.prototype.populate() returns a Query object on which you need to run .exec(), try this:
Story.find({})
.populate('category', 'title')
.exec()
.then(stories => {
res.render('stories/add', {
stories: stories
});
});
It was problem with that how I want to use it. Code is working

Mongoose discriminator not calling parent pre save hook

So I have 2 models:
Transaction.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { User } = require('./index');
const TransactionSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
amount: {
type: Number,
required: true
},
userAmount: {
type: Number,
required: true
}
}, { discriminatorKey: 'kind' });
TransactionSchema.pre('save', async function () {
console.log('entered here?');
const user = await User.findById(this.user);
const modifier = this.kind == 'INCOME' ? 1 : -1;
const amount = user.balance + (modifier * this.amount);
this.userAmount = amount;
user.balance = amount;
await user.save();
});
module.exports = mongoose.model('Transaction', TransactionSchema);
Income.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Transaction = require('./Transaction');
const Income = Transaction.discriminator('INCOME', new Schema({
client: {
type: Schema.Types.ObjectId,
ref: 'Client'
}
}))
module.exports = Income;
As you can see, Income is discriminator of Transaction.
Now I defined pre save hook on Transaction, but when I call Income.create(), that hook is never called, and I just get the error: userAmount is required (which I wanna set inside pre save).

Resources