Trouble with mongoDB Ref -> trying to ref array of diferent model - node.js

so i'm trying ref a array of daysOff (Ferias model) as a fiel in a User model,
i'm new to MongoDB and mongoose, and i'm trying to build a API that manages a company workers days off.
I apologyse in advance for the "format" of this question but it's the very first time that I post a question in StackOverflow :)
Thanks u all!
const mongoose = require("mongoose");
const moment = require("moment");
const feriasSchema = mongoose.Schema(
{
user: {
type: mongoose.Types.ObjectId,
required: true,
ref: "User",
},
firstName: {
type: String,
ref: "User",
},
lastName: {
type: String,
ref: "User",
},
workerNumber: {
type: Number,
ref: "User",
},
sectionOfWork: {
type: String,
ref: "User",
},
totalFerias: {
type: Number,
required: true,
},
//this is the field i want to add in User model as an array of (dates format DD/MM/YYYY)
ferias: {
type: [String],
//default: [Date],
required: true,
},
tipoFerias: {
type: String,
required: true,
},
modo: {
type: String,
required: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Ferias", feriasSchema);
// USER MODEL
const userSchema = mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: [true, "Please enter a valid email address"],
unique: true,
},
password: {
type: String,
required: [true, "Please enter a password"],
},
workerNumber: {
type: Number,
required: true,
unique: true,
},
sectionOfWork: {
type: String,
required: true,
},
chefia: {
type: String,
required: true,
},
//this is the field i want to be an array (from Ferias model)
ferias: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Ferias",
}],
role: {
type: String,
required: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", userSchema);
what am i doing wrong?
i'm getting and empty array ...
in express I can send the questioned data separately but u want to send a json to some frontend with all the fields of a user, with the "ferias" array present.

Related

mongoose schema not sending correct address details

was wondering if someone had an of how I can develop a schema for the following model below, all fields are required.
Data I want captured
{
"name": "The Shop",
"address": {
"line_one":"123 Joe Blogs Ave",
"line_two":"District 1",
"city":"Random city",
"postcode/zip":"AB12 3BJ"
},
"coverImage":"imageURL",
"rating": 4.5
}
const placeSchema = mongoose.Schema({
name: {
type: String,
required: true,
address: {
line_one: {
type: String,
required: true,
},
line_two: {
type: String,
required: true,
},
city: {
type: String,
required: true,
},
postcode: {
type: String,
required: true,
},
},
},
coverImage: {
type: String,
rating: {
type: mongoose.Types.Decimal128,
},
},
});
When posting the data I only find returned the name, coverimage, _id and __v.
You would use subdocuments for this, or Nested Schemas:
So basically for nested Objects you define another Schema, and then tell the main schema that the field is of type subschema
const addressSchema = mongoose.Schema({
line_one: {
type: String,
required: true,
},
line_two: {
type: String,
required: true,
},
city: {
type: String,
required: true,
},
postcode: {
type: String,
required: true,
}
})
const placeSchema = mongoose.Schema({
name: {
type: String,
required: true,
address: {
type: addressSchema,
required: true
}
},
coverImage: {
type: String,
rating: {
type: mongoose.Types.Decimal128,
},
},
});
```

Mongoose: query to get nested multiple related data

I'm new to NoSQL, in this case is MongoDB. I'm trying to make an API using ExpressJS and Mongoose. that have some data models
User.js
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
min: 3,
max: 50,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: Schema.Types.ObjectId,
ref: "Image",
},
}
Image.js
const ImageSchema = new mongoose.Schema(
{
desc: {
type: String,
},
url: {
type: String,
},
},
{ timestamps: true }
)
Post.js
const PostSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
desc: {
type: String,
max: 300,
required: true,
},
images: [
{
type: Schema.Types.ObjectId,
ref: "Image",
},
],
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment",
},
],
}
)
Comment.js
const CommentSchema = new mongoose.Schema(
{
user: {
type: Schema.Types.ObjectId,
ref: "User",
},
text: {
type: String,
required: true,
trim: true,
},
}
Now I want to perform a query that gets all comments based on specific postId. And the response data must include User data and image url that related to User. I tried this to get comment data
const comments = await Comment.find({post: req.params.postId}).populate("user")
It returned Comment with User data, but not include Image. How do I perform that query?
Try this (using the pupulate method with object configuration):
const comments = await Comment.find({post: req.params.postId}).populate({
path: 'user',
populate: {
path: 'profilePicture'
}
})
Here you can also select particular fields of each schema for example.
Let me know if it works for you.
Reference

creating an attribute that contains a list of objects node js

Im new using node js , what im trying to do is creating an attribute that contains a list of projects in the userSchema so i can display the projects when the user log in in my electron app
this is my userschema :
var UserSchema = new Schema(
{
username: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true,
},
nom: {
type: String,
required: true,
},
prenom: {
type: String,
required: true,
},
verif_code: {
type: String,
required: false,
},
}, { timestamps: { createdAt: 'created_at' } });
and this is my projectSchema :
var ProjectSchema = new Schema(
{
description: {
type: String,
},
useremail: {
type: String,
},
imageurl: {
type: String,
},
var UserSchema = new Schema(
{
username: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true,
},
nom: {
type: String,
required: true,
},
prenom: {
type: String,
required: true,
},
verif_code: {
type: String,
required: false,
},
projects: [{type: Types.ObjectId, ref: 'projects'}],//projects is name of table in database
}, { timestamps: { createdAt: 'created_at' } });

Populate returns whole parent document

I just started learning express and mongodb. I recently faced the kind of problem, I'm trying to select all the subdocuments which are inside of Room model.
const books = await Room.find().populate('book');
But it returns whole room document when i want to select only bookings field.
Here's the book schema
const bookSchema = new mongoose.Schema({
startDate: {
type: Date,
required: true,
},
endDate: {
type: Date,
required: true,
},
name: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
});
module.exports = mongoose.model("book", bookSchema)
And here's the room schema
const roomSchema = new mongoose.Schema({
currentlyReserved: {
type: Boolean,
default: false,
},
people: {
type: Number,
required: true,
},
roomNumber: {
type: Number,
required: true,
},
pricePerPerson: {
type: Number,
required: true,
},
reservedUntil: {
type: Date,
default: null,
},
reservedBy: {
type: String,
default: null,
},
bookings: {
type: [{ type: mongoose.Schema.Types.ObjectId, ref: "book" }],
},
});
module.exports = mongoose.model("room", roomSchema);
You can project with with second arg to find().
https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection
const books = await Room.find({}, {bookings: 1}).populate('bookings');

How to populate object having array of object in mongoose?

I want to populate the adminId path to User Model.
Here is the code
adminInfo: {
_id: false,
adminId: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
}
Here is a part of user schema:
// user schema
const UserSchema = new mongoose.Schema({
name: {
firstName: {
type: String,
trim: true,
required: true,
},
lastName: {
type: String,
trim: true
}
},
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
phone: {
type: String,
trim: true,
minlength: 10,
},
password: {
type: String,
trim: true,
required: true,
minlength: 6
}
});
I have tried using .populate('adminInfo.adminId') but it's giving empty array [] whereas .populate('adminInfo') giving array of admins ids but not getting populated to User model
i don't think there is any problem with .populate('adminInfo.adminId') method.
are you sure that ref field is in CamelCase .
If not, try to change ref field ->
adminInfo: {
_id: false,
adminId: [{
type: Schema.Types.ObjectId,
ref: 'user'
}]
}

Resources