How to add array of objects to mongoDB model - express

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.

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 push items into an array in mongoose

I have a problem where I am creating a user and want to save some items associated to this user at the same time.
I have managed to get it where I can create an item and reference the user_id associated to that item but I cant work out how to push all the items the user has into the User schema.
I have tried looping through req.body.taken and adding to user schema but I just get null returned.
router.post('/data', async (req, res) => {
var user = new User({
name: req.body.name,
website: req.body.website,
})
user.save(function (err) {
if (err) {
return next(err);
}
})
req.body.taken.forEach((item) => {
var item = new Item({
x: item.x,
y: item.y,
xSize: item.xSize,
ySize: item.xSize,
user: user,
imageSource: item.imageSource,
user: user
}
)
item.save(function (err) {
if (err) {
return next(err);
}
})
})
const UserSchema = new Schema(
{
id: Number,
name: String,
website: String,
items: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Item'
}]
},
{ timestamps: true }
);
const ItemSchema = new Schema(
{
id: Number,
x: Number,
y: Number,
xSize: String,
ySize: String,
imageSource: String,
user: { type: mongoose.Schema.ObjectId, ref: 'User' }
},
{ timestamps: true }
);
User.find({})
.populate('items')
.exec(function(error, items) {
console.log(items)
})
When I call User find I want to get all items associated to that user (which will be an array as req.body.taken is an array of items.
There's a few issues here.
you are not waiting for user.save, theres a good chance all your items are being saved before the user doc is even returned. you should either await for promise on user.save or put the items.forEach loop in the callback. also you are saving the entire objet and not the user._id returned which mongoose wont allow as it does not match the scheme. making the creation fail.
You are not saving the items array in your user, how can you expect to populate that field if its empty. the flow of your code needs to change a little in order to allow you to update this field.

Trouble Rendering Mongoose find() to EJS

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;

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);
});
});