Trouble Rendering Mongoose find() to EJS - express

I'm trying to load and display several work entries from my MongoDB database using mongoose and Express and I'm running into trouble.
When I try to pass the results to my .ejs file, I get the error that the variable is not defined.
For some reason, it works when I pass individual objects to the .ejs file.
Here's what is working, but isn't useful
router.get('loadEntries', (req,res) => {
Entry.find({}, function(err, data) {
data.forEach(function(item) {
res.render('loadEntries',{firstName:item.firstName});
}
});
});
//ejs file. Very basic, just to capture the data
<p>
<%=firstName%>
</p>
Here's what I would like to do, but isn't working
router.get('loadEntries', (req,res) => {
Entry.find({}, function(err, data) {
res.render('loadEntries',{result:data});
});
});
//ejs file
<p>
<%result.forEach(function(item) { %>
First name: <%=item.firstName%>
Last name: <%=item.lastName%>
<%})%>
</p>
My mongoose model
const mongoose = require('mongoose');
const EntrySchema = new mongoose.Schema({
//hours, room, buliding, note
hours: {
type: Number,
required: true
},
room: {
type: String,
required: true
},
building: {
type: String,
required: true
},
note: {
type: String,
required: false
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
}
});
const Entry = mongoose.model('Entry', EntrySchema);
module.exports = Entry;

Related

Custom id generation for Redis-OM nodejs using provided entity data

for example:
const fooSchema = new Schema(Foo, {
userId: { type: 'number' },
channelId: { type: 'number' }
}, {
idStrategy: () => `${userId}${channelId}`
});
Is it possible to provide the idStrategy function with the entity data?

how to declare pageSize in axios get api for pagination vue 3 while it has the data

I'm using Tailwind Pagination for my vue app. I'm currently getting all the data from axios get, and it also gets page: 1 and pageSize: 200 from api.
but they've told me that I have to send the numbers myself and I'm stuck in the middle of it...
I'm getting data like:
in Employee page:
async getUser() {
await this.$store.dispatch("axiosGet", {url: 'identity/api/employees'}).then(response => {
if (response.status === 'error') return
this.userList = response.data.data.data
this.page = response.data.data.page
this.pageSize = response.data.data.pageSize
this.totalCount = response.data.data.totalCount
console.log(response.data.data)
})
},
and then, in Tailwind component passed data through:
in Table component:
then, inside the VPagination component it's what's happening:
<VueTailwindPagination
:current="page"
:total="totalCount"
:per-page="pageSize"
#page-changed="pageChange($event)">
</VueTailwindPagination>
then:
props: {
userList: {type: Object},
page: {type: Number},
pageSize: {type: Number},
totalCount: {type: Number}
},
methods:
pageChange(pageNumber) {
this.currentPage= pageNumber
},
so, there's only one page and no pagination is possible.
the Swagger is like this:
Can anyone help me with the problem?
You can get your data like this:
async getUser() {
await this.$store.dispatch("axiosGet",
{url: `identity/api/employees?page=${1}&pageSize=${10}`})
.then(response => {})
},
but you need to replace the constant value with your local variables...

How to add array of objects to mongoDB model

I have a model which represents a menu for a restaurant, within that model I have an array for the items in the menu. I am not sure how to add menu items to my menu model using express, I bolded the line where I am not sure what to write.
This is the menu model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const FoodItemSchema = new Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
Category: { type: String, required: false },
Quantity: { type: String, required: false },
});
const MenuSchema = new Schema({
restaurant_id: { type: mongoose.Schema.Types.ObjectId, ref: "restaurant" },
items: [FoodItemSchema],
dateCreated: { type: String, required: false },
});
module.exports = mongoose.model("menu", MenuSchema);
And this is my express function which I am using to add menus to my database, I am unsure what to add for the array of menu items within the function.
exports.sendMenuData = (req, res) => {
const menu = new Menu({
restaurant_id: req.body.restaurant_id,
**items: [FoodItemSchema]**, //Not sure what to write here in terms of req
dateCreated:req.dateCreated,
});
menu
.save()
.then((data) => {
console.log(data);
res.send(data);
})
.catch((err) => {
console.log(err);
});
};
You need to pass through postman or whatever app you are using to acces your db the array of food items.
Example:
items: [req.body.theNameYouWant],
In postman:
theNameYouWant: {name:"Hot dog",price: 3,...(You must place here all the atributes of FoodItemSchema)}
Otherwise, you can also use operators such $addToSet $push which will allow you to introduce FoodItemSchema in the array.

How do I set a default value or options of a Foreign Key in a 'BelongsTo' association in Sequelize?

I have a seemingly common problem with sequelize. For context I am trying to assign a default role to each user that is created. Essentially each user's role should be set to default user when they are first registered.
I would like to be able to simply define this default value in my Models file as you would with normal fields but, I can't seem to find the correct syntax.
This is what my User model currently looks like:
'use strict';
import { Sequelize } from 'sequelize';
export default (sequelize: Sequelize) => {
const Users = sequelize.define(
'Users',
{
email: {
type: Sequelize.STRING,
allowNull: false
},
some_foreign_id: {
type: Sequelize.STRING,
allowNull: false
}
},
{}
);
Users.associate = models => {
// associations can be defined here
Users.belongsTo(models.Roles, { as: 'Role' });
};
return Users;
};
Currently I am just making a query to find the role with the name default role and adding it to my user as it is created. However, I feel that query is unnecessary.
Based on the google autofill suggestions it seems like a lot of people have this problem without any clear solution.
[EDIT]
My role model (heh) currently looks like this:
import { Sequelize } from 'sequelize';
export default (sequelize: Sequelize) => {
const Roles = sequelize.define(
'Roles',
{
name: {
type: Sequelize.STRING,
allowNull: false
}
},
{}
);
Roles.associate = models => {
// associations can be defined here
// SO note: This association is for my permissions. Should have nothing to do with my User association.
Roles.belongsToMany(models.Permissions, { through: 'RolePermission' });
};
return Roles;
};
Old Answer, see updated below.
Hm.. I actually have the same problem right now, and I don't know wheter this is a good solution or not. But my models currently a bit the same with yours..
Here is my user model
// importing sequelize and stuff..
User.init({
id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: STRING,
allowNull: false
},
email: {
type: STRING,
allowNull: false,
unique: true,
validation: {
isEmail: {
msg: 'Not a valid email address'
}
}
},
password: {
type: STRING,
allowNull: false
},
RoleId: {
type: INTEGER,
allowNull: false,
defaultValue: 2
}
}, {/* stuff */})
Notice the defaultValue property in RoleId.
And now it is my time to show you my role model (jokes unintended)
Role.init({
id: {
type: INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: STRING,
allowNull: false
},
level: {
type: INTEGER,
allowNull: false
}
}, {/* stuff */})
And in my case, when I do POST /login in my user controller
// POST /users
create(req, res) {
const { name, email, password } = req.body
return User.create({ name, email, password })
.then(createdUser => res.json(createdUser))
.catch(err => res.status(503).json({ msg: err }))
}
Here is the result:
Bewarned, I was just trying stuff and had no idea if this results are intended in sequelize. It also has been a while since I used Sequelize and notice that they had changed the naming of foreign key. As far as I remember it used to be camelCase, now it's PascalCase. Maybe others can help explaining those. My sequelize version is 5.15.0 at the time I wrote this.
Thank you :)
Whoops - Updated in just a few minutes..
Lucky me, I found this issue on GitHub as How to require a foreign key to be not null #2837 .
TL;DR
When associating between models you can use this..
User.belongsTo(Role, {
foreignKey: {
/* use this like `sequelize.define(...)` */
allowNull: false,
defaultValue: 2
}
})
When you query for User, just do an include
User.find({
where: {
id: 1
},
include: [{
model: Role,
as: 'Role'
}]
}).then(foundUserWithRole => {
// do something here
}).catch(err => {});
This will return the role attached to the User every time you query for the user. Therefore you don't need to make a separate query for role.
Your User table is going to get a roleId column in it from the associate function. I believe you can just define that property in the User model and give it a default value property.

mongoose populate generic array of ObjectId without ref

I'm using mongoose 4.6.6, express 4.13, passport 0.3.
I have the next mongoose Schema
var userSchema = new Schema({
nombre: String,
apellidos: String,
email: String,
pass: String,
fecha_registro : { type: Date, default: Date.now },
rol_list: [Schema.Types.ObjectId], // generic array of objectId
deleted: {type: Boolean, default: false}
});
module.exports = mongoose.model('User', userSchema);
When I search a user and try to populate the "rol_list" array, is always empty.
I have looked in mongo the users are well filled, but mongoose return it empty.
passport.deserializeUser(function(id, done) {
User.findById(id)
.populate('rol_list')
.exec(function(err, user) {
console.log(user);
done(err, user);
});
});
The console.log(user) show always the array rol_list empty.
If I assign a reference to the ObjectId like:
rol_list: [{ type: Schema.Types.ObjectId, ref: 'Rol1' }]
than is correct filled, logically only with the element "Rol1".
Any idea?
There is an option in .populate(...) mongoose function that allow you to specify the model that's behind the ObjectId.
#example
Conversation.find().populate('creator', null, 'User2').exec(callback);
Stack overflow post: mongoose-populate-field-without-ref-option
If you want array of only object ids then don't use populate with it.
like:
passport.deserializeUser(function(id, done) {
User.findById(id)
.exec(function(err, user) {
console.log(user);
done(err, user);
});
});