using #each in handlebars not working - node.js

I have a var with products and if I console log it out it shows this.
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: null,
opts: { bufferCommands: true, capped: false },
name: 'products',
collectionName: 'products',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
queue: [],
buffer: true,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: {}, _posts: {} },
base:
Mongoose {
connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'Product',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
discriminators: undefined,
schema:
Schema {
obj: [Object],
paths: [Object],
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [Object],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: [Object],
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'products',
collectionName: 'products',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
insertMany: [Function] },
schema:
Schema {
obj:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object] },
paths:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [ [Object], [Object], [Object], [Object] ],
_indexes: [],
methods: {},
statics: {},
tree:
{ imagePath: [Object],
title: [Object],
description: [Object],
price: [Object],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: { hooks: [Object], kareemHooks: [Object] },
options:
{ retainKeyOrder: false,
typeKey: 'type',
id: true,
noVirtualId: false,
_id: true,
noId: false,
validateBeforeSave: true,
read: null,
shardKey: null,
autoIndex: null,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
'$globalPluginsApplied': true },
op: 'find',
options: { retainKeyOrder: false },
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'products',
collectionName: 'products',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
collectionName: 'products' },
_traceFunction: undefined,
_castError: null,
_count: [Function],
_execUpdate: [Function],
_find: [Function],
_findOne: [Function],
_findOneAndRemove: [Function],
_findOneAndUpdate: [Function] }
I am trying to use #each to get the products and show lets say the title first.
Here is my method in index js using node
var express = require('express');
var router = express.Router();
var Product = require('../models/product');
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find({}, function (err, products) {
// check for and handle query errors
if (err) {
console.error('Product.find() error', err);
return next(err);
}
// continue to render the view with `products` available
console.log(products);
res.render('shop/index', { title: 'Shopping Cart', products: products });
});
});
module.exports = router;
And here is the foreach sentence at index.hbs
{{#each products}}
<p>{{products.price}}</p>
{{/each}}
I tried different ways like #each this and then getting it but non seem working.
Just incase if needed when I search in the db
> db.products.find()
{ "_id" : ObjectId("5855c55482d8722419e21a7d"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "weeee", "description" : " AWeeesomeee", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a7e"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "Gowwww", "description" : " this is great", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a7f"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "killaa crw", "description" : " i love it", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a80"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "joker", "description" : " kill em", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a81"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "harley", "description" : " naughtttyyy", "price" : "15", "__v" : 0 }
{ "_id" : ObjectId("5855c55482d8722419e21a82"), "imagePath" : "https://upload.wikimedia.org/wikipedia/en/thumb/5/5e/Gothiccover.png/250px-Gothiccover.png", "title" : "suicide", "description" : " squad", "price" : "15", "__v" : 0 }
> db.products.count()
6
App.js file
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var routes = require('./routes/index');
var app = express();
app.connect('localhost:27017/shopping');
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout : 'layout', extname: '.hbs' }));
app.set('view engine', '.hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

Mongoose' model.find() doesn't return the results directly as Mongo's command-line does.
var products = Product.find();
It expects a callback function to be provided either to it directly, following the conditions, or provided to a method of the Query object it returns:
function proceedWithProducts(err, products) {
if (err) {
// handler query error
} else {
// use products
}
}
// a couple options...
Product.find({}, proceedWithProducts);
Product.find().exec(proceedWithProducts);
Within the route:
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find({}, function (err, products) {
// check for and handle query errors
if (err) {
console.error('Product.find() error', err);
return next(err);
}
// continue to render the view with `products` available
console.log(products);
res.render('shop/index', { title: 'Shopping Cart', products: products });
});
});

Related

server doesn't send response for Sequelize many to many relationship query

I am new to sequelize and node js. I have been trying to implement Sequelize Many-to-Many Association using node.js, express with PostgreSQL database following this tutorial. I have implemented a single table and retrieve data correctly without any issue. But in many-to-many relationships, I can only print data to console and in postman and chrome, it keeps loading around a minute and wait without loading data. Here are my code files.
db config file
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
define: {
timestamps: true,
freezeTableName: true
},
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.actor = require("./actor.model.js")(sequelize, Sequelize);
db.film = require("./film.model.js")(sequelize, Sequelize);
db.film_actor = require("./film_actor.model.js")(sequelize, Sequelize);
db.film.belongsToMany(db.actor, {
through: db.film_actor,
as: "actors",
foreignKey: "film_id",
});
db.actor.belongsToMany(db.film, {
through: db.film_actor,
as: "films",
foreignKey: "actor_id",
});
module.exports = db;
filmController file
const db = require("../models");
const Film = db.film;
const Actor = db.actor;
//find all films including actors
exports.findAll = () => {
return Film.findAll({
include: [
{
model: Actor,
as: "actors",
attributes: ["first_name", "last_name"],
through: {
attributes: [],
}
},
],
})
.then((film) => {
console.log(film[5]);
return film;
})
.catch((err) => {
console.log(">> Error while retrieving films: ", err);
});
};
// find film by film id
exports.findById = (req, res) => {
const film_id = req.params.id;
return Film.findByPk(film_id, {
include: [
{
model: Actor,
as: "actors",
attributes: ["first_name", "last_name"],
through: {
attributes: [],
}
},
],
})
.then((films) => {
return films;
})
.catch((err) => {
console.log(">> Error while finding film: ", err);
});
};
film.route file
module.exports = app => {
const film = require("../controllers/film.controller.js");
var router = require("express").Router();
// Retrieve all films
router.get("/films", film.findAll);
// Retrieve a single actor with id
router.get("/films/:id", film.findById);
app.use('/api', router);
};
server.js file
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const filmController = require("./app/controllers/film.controller");
const app = express();
const db = require("./app/models");
db.sequelize.sync();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
db.sequelize.sync().then(() => {
// run();
});
require("./app/routes/actor.routes")(app);
require("./app/routes/film.routes")(app);
// app.get('/films',filmController.findAll);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
As per my understanding, the issue should be about the routing. I created route for many to many associations as the same way I did for singe table(actor) but this problem occurred. I put a console log under findAll() method in filCcontroller and it prints the data in the console along with the query.
This is the output on my console
Executing (default): SELECT "film"."film_id", "film"."title", "film"."description", "film"."release_year", "film"."language_id", "film"."rental_duration", "film"."length", "actors"."actor_id" AS "actors.actor_id", "actors"."first_name" AS "actors.first_name", "actors"."last_name" AS "actors.last_name" FROM "film" AS "film" LEFT OUTER JOIN ( "film_actor" AS "actors->film_actor" INNER JOIN "actor" AS "actors" ON
"actors"."actor_id" = "actors->film_actor"."actor_id") ON "film"."film_id" = "actors->film_actor"."film_id";
film {
dataValues: {
film_id: 166,
title: 'Color Philadelphia',
description: 'A Thoughtful Panorama of a Car And a Crocodile who must Sink a Monkey in The Sahara Desert',
release_year: 2006,
language_id: 1,
rental_duration: 6,
length: 149,
actors: [
[actor], [actor],
[actor], [actor],
[actor], [actor],
[actor]
]
},
_previousDataValues: {
film_id: 166,
title: 'Color Philadelphia',
description: 'A Thoughtful Panorama of a Car And a Crocodile who must Sink a Monkey in The Sahara Desert',
release_year: 2006,
language_id: 1,
rental_duration: 6,
length: 149,
actors: [
[actor], [actor],
[actor], [actor],
[actor], [actor],
[actor]
]
},
_changed: Set {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [ [Object] ],
includeNames: [ 'actors' ],
includeMap: { actors: [Object] },
includeValidated: true,
attributes: [
'film_id',
'title',
'description',
'release_year',
'language_id',
'rental_duration',
'length'
],
raw: true
},
isNewRecord: false,
actors: [
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
}
]
}
any help would be greatly appreciated.

NodeJS + mongoose - user dynamic database globally

I am using NodeJS, ExpressJS, express-session, connect-mongo and mongoose. I want to create a database for every user. On login the database connection should be globally to use.
This is the: loginController
exports.loginPost = (req, res, next) => {
const email = req.body.email;
const pass = req.body.password;
const pin = req.body.pin;
if (email && pass && pin) {
User.findOne({ email })
.then(u => {
bcrypt.compare(pass, u.password, (err, result) => {
if (!err) {
bcrypt.compare(pin, u.pin, (err2, result2) => {
if (!err2) {
let msg = {};
global.userDB = null;
msg.success = [{ text: "You are now logged in..." }];
req.session.loggedIn = true;
req.session.userId = u._id;
req.session.role= u.role;
const Mongoose = require("mongoose").Mongoose;
const inst = new Mongoose();
let db = "user-" + orgid;
global.userDB = inst.connect(
"mongodb://localhost:27017?authSource=dbWithUserCredentials",
{
useNewUrlParser: true,
auth: { authSource: "admin" },
user: "root",
pass: "root",
dbName: db,
autoReconnect: true
}
);
return res.redirect("/");
} else {
console.log(err2);
}
});
} else {
return res.render("login", {
req,
msg: null
});
}
});
})
.catch(err => {
return res.render("login", {
req,
msg: err
});
});
}
};
This is the adressModel:
const aschema = global.userDB.Schema;
var AdressSchema = new aschema({
name: {
type: String
}
});
var Address = global.userDB.model("Adress", AdressSchema);
module.exports = Address;
When I'm running a page where I'm using this model, i see this on the console when I'm using this command: "console.log(global.userDB)";
NativeConnection {
base:
Mongoose {
connections: [ [Circular] ],
models: {},
modelSchemas: {},
options: { pluralization: true },
plugins: [ [Array], [Array], [Array] ] },
collections: {},
models: {},
config: { autoIndex: true },
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: 'root',
pass: 'root',
name: 'user-undefined',
options:
{ pass: 'root',
user: 'root',
auth: { authSource: 'admin' },
useNewUrlParser: true,
db: { forceServerObjectId: false, w: 1 },
server: { socketOptions: {}, auto_reconnect: true },
replset: { socketOptions: {} },
mongos: undefined },
otherDbs: [],
states:
[Object: null prototype] {
'0': 'disconnected',
'1': 'connected',
'2': 'connecting',
'3': 'disconnecting',
'4': 'unauthorized',
'99': 'uninitialized',
disconnected: 0,
connected: 1,
connecting: 2,
disconnecting: 3,
unauthorized: 4,
uninitialized: 99 },
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db:
Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ databaseName: 'user-undefined',
dbCache: {},
children: [],
topology: [Server],
options: [Object],
logger: [Logger],
bson: BSON {},
authSource: undefined,
readPreference: undefined,
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] } }
Can someone say, why i get an 'undefined' in the database-name, but when I console.log the 'db'-variable there is the correct user._id.
Thanks!

CastError: Cast to ObjectId failed for value in mongoose operation

i have used a middleware called checktoken in every routes except login route in my code . when i hit login url it logged me in where there is to token checked. but now if i wish to go to any route after logging in it restricts me inside checkToken middleware.i have used jsonwebtoken module to generate token and verify it.but my code failed to find users.here is my checktoken middle ware code
if (token) {
try {
var decoded = jsonwebtoken.verify(token, jwt_key);
req.user = decoded.user;///
console.log(req.user._id);// i get id here and from this id i can find user in database
UserSchema.findOne({
_id: req.user._id
})///this query failed finding result
.exec(function(err, result) {
if (err) {
console.log(err);//error gets output in the console.
res.status(500);
return res.json({
result: err
});
}
if (result) {
return next();
} else {
res.status(400);
return res.json({
message: "The user does not exists"
});
}
});
} catch (err) {
res.status(403);
res.json({
message: "Invalid Token"
});
}
} else {
res.status(401);
res.json({
message: "No token provided"
});
}
the error message i get in console is
{ [CastError: Cast to ObjectId failed for value "5875d76e1df97635623061c5" at path "_id" for model "User"]
message: 'Cast to ObjectId failed for value "5875d76e1df97635623061c5" at path "_id" for model "User"',
name: 'CastError',
stringValue: '"5875d76e1df97635623061c5"',
kind: 'ObjectId',
value: '5875d76e1df97635623061c5',
path: '_id',
reason: undefined,
model:
{ [Function: model]
hooks: Kareem { _pres: {}, _posts: {} },
base:
Mongoose {
connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'User',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'myschoolbus_demo',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db: [Object] },
discriminators: undefined,
schema:
Schema {
obj: [Object],
paths: [Object],
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: [Object],
inherits: {},
callQueue: [Object],
_indexes: [],
methods: [Object],
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: [Object],
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
insertMany: [Function] } }
i cannot figure out where i am wrong. any suggestions are highly appreciated.
Strip quotes from your id. Your error says:
stringValue: '"5875d76e1df97635623061c5"',
See the " at start and end? It's part of the string. I don't know if your middleware, or frontend or whoever puts it, so either strip it yourself or pass it before.
Try this:
UserSchema.findOne({
_id: req.user._id.replace(/"/g, '')
})

Deploying Node-expressjs app in lambda - [Error: socket hang up] code: ECONNRESET

I am trying to deploy my Expressjs application into lambda, but i am getting below error. Please try to me to resolve this error.
lambda response:
{
"statusCode": 502,
"body": "",
"headers": {}
}
lambda log (it contains console of mongo connection and error)
NativeConnection {
base:
Mongoose {
connections: [ [Circular] ],
plugins: [],
models: { Student: [Object] },
modelSchemas: { Student: [Object] },
options: { pluralization: true } },
collections:
{ student:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'student',
collectionName: 'student',
conn: [Circular],
queue: [],
buffer: false,
emitter: [Object] } },
models:
{ Student:
{ [Function: model]
hooks: [Object],
base: [Object],
modelName: 'Student',
model: [Function: model],
db: [Circular],
discriminators: undefined,
schema: [Object],
collection: [Object],
Query: [Object],
'$__insertMany': [Function],
insertMany: [Function] } },
config: { autoIndex: true },
replica: false,
hosts: null,
host: '1.0.0.0.0',
port: 3000,
user: undefined,
pass: undefined,
name: 'sudentdb',
options:
{ mongos: {},
db: { safe: true, forceServerObjectId: false },
auth: {},
server: { socketOptions: {}, auto_reconnect: true },
replset: { socketOptions: {} } },
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db:
EventEmitter {
domain: null,
_events:
{ close: [Function],
error: [Function],
reconnect: [Function],
timeout: [Function],
open: [Function],
parseError: [Function] },
_eventsCount: 6,
_maxListeners: undefined,
s:
{ databaseName: 'studentdb',
dbCache: {},
children: [],
topology: [Object],
options: [Object],
logger: [Object],
bson: {},
authSource: undefined,
readPreference: undefined,
bufferMaxEntries: -1,
parentDb: null,
pkFactory: undefined,
nativeParser: undefined,
promiseLibrary: [Function: Promise],
noListener: false,
readConcern: undefined },
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
_listening: true },
_events:
{ connected: [Function],
error: [Function],
disconnected: [Function] },
_eventsCount: 3 }
{ [Error: socket hang up] code: 'ECONNRESET' }
student.model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var studentSchema = new Schema({
name: String,
rollnumber: Number,
},{collection:"student"});
module.exports = mongoose.model('Student', studentSchema);
api/student(REST API - GET method)
exports.index = function(req, res) {
console.log(mongoose.connection)
Student.findOne({},function(err,doc){
if(err){
return res.json("error found");
}else{
return res.json(doc);
}
});
};
lambda.js
'use strict'
const awsServerlessExpress = require('aws-serverless-express');
const app = require('./bin/www');
const server = awsServerlessExpress.createServer(app);
exports.handler = (event,context)=>{
console.log("EVENT: " + JSON.stringify(event));
awsServerlessExpress.proxy(server,event,context);
}

Writing A Mongoose Plug In- plugin() a method?

I am interested in writing a mongoose plug in to make all fields required. I know there are other ways to do this, but I like the idea of writing my own plug in.
From docs http://mongoosejs.com/docs/plugins:
// game-schema.js
var lastMod = require('./lastMod');
var Game = new Schema({ ... });
Game.plugin(lastMod, { index: true });
but when I create a model from my schema and look at the properties, I don't see a plugin() method:
var mongoose = require('mongoose');
var CpuSchema = require("../schemas/cpu");
var Cpu = mongoose.model('Cpu', CpuSchema);
console.log(Cpu);
module.exports = Cpu;
one#demo ~/cloudimageshare-monitoring/project $ node /home/one/cloudimageshare-monitoring/project/app/data/models/cpu.js
{ [Function: model]
base:
{ connections: [ [Object] ],
plugins: [],
models: { Cpu: [Circular] },
modelSchemas: { Cpu: [Object] },
options: { pluralization: true } },
modelName: 'Cpu',
model: [Function: model],
db:
{ base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
collections: { cpus: [Object] },
models: {},
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
discriminators: undefined,
schema:
{ paths:
{ timeStamp: [Object],
avaiable: [Object],
status: [Object],
metrics: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
statics: {},
tree:
{ timeStamp: [Object],
avaiable: [Function: Boolean],
status: [Function: String],
metrics: [Object],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
options:
{ id: true,
noVirtualId: false,
_id: true,
noId: false,
read: null,
shardKey: null,
autoIndex: true,
minimize: true,
discriminatorKey: '__t',
versionKey: '__v',
capped: false,
bufferCommands: true,
strict: true,
pluralization: true },
_events: {} },
options: undefined,
collection:
{ collection: null,
opts: { bufferCommands: true, capped: false },
name: 'cpus',
conn:
{ base: [Object],
collections: [Object],
models: {},
replica: false,
hosts: null,
host: null,
port: null,
user: null,
pass: null,
name: null,
options: null,
otherDbs: [],
_readyState: 0,
_closeCalled: false,
_hasOpened: false,
_listening: false },
queue: [ [Object] ],
buffer: true } }
Here on the model, I don't see a plugin() method.
The plugin method is defined on the Schema class and you can see it on your CpuSchema object.
On your Cpu model you can get it by calling
console.log(Cpu.schema.plugin)
From the mongoose source code on GitHub:
/**
* Registers a plugin for this schema.
*
* #param {Function} plugin callback
* #param {Object} opts
* #see plugins
* #api public
*/
Schema.prototype.plugin = function (fn, opts) {
fn(this, opts);
return this;
};
When you pass your plugin function to it it simply executes the function and passes the schema reference into it.

Resources