I'm trying to find whether a given EventID exists in the attendsTo array of a user. Is there any way to check for this condition in mongoose? Thanks a lot!
User Schema:
const userSchema = mongoose.Schema(
{
username: {
type: String,
required: [true, 'Please add a username'],
},
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
},
password: {
type: String,
required: [true, 'Please add a password'],
},
language: {
type: String,
default: "English"
},
attendsTo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Event' }],
friends: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
pendingFriends: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
images:[{data:Buffer,contentType: String}],
profilePic: [{data:Buffer, contentType:String}],
status: String,
},
{
timestamps: true,
}
)
Related
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.
I am building a user model in mongoose, nodesjs where the each user has set of contacts which are actually users, each contact is a user.
I have two approaches
Approach 1
Is to add the contacts as an array of user objects to reference User model in the user model as an array of contacts but i want to determine the Date and time of when was the contact was added, i don't know how to add that
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please enter a name'],
},
username: {
type: String,
match: [
/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/,
'Please enter a valid user name',
],
},
password: {
type: String,
required: [true, 'Please enter a password'],
minLength: 6,
select: false,
},
role: {
type: String,
enum: ['user'],
default: 'user',
},
resetPasswordToken: String,
resetPasswordExpire: Date,
allowAutoApproveContacts: {
type: Boolean,
default: false,
},
createdAt: {
type: Date,
default: Date.now,
},
contacts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
],
});
**Approach 2 **
is to create a new model Contact and reference the user model as user and the User model again as the contact, and add the addedAt Date to determine when was the contact was added and maybe add other properties
const ContactSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
contact: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
addedAt: {
type: Date,
default: Date.now,
},
autoAllowed: Boolean,
});
Can you please help me with which approach is the correct approach or if you can suggest a new one
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'
}]
}
I'm new to building rest api's with mongoose and express and have a question on how to use refPath correctly on my Models files and allowing for an array of items.
Below I have included the code for a model (built thus far) and would love any input on if I'm even close to building this correctly.
I will also include a screenshot that visually depicts the relationships I'm trying to create.
Those who answer questions here are GODS and I appreciate all the help this community has given me over the years!
const mongoose = require("mongoose");
const slugify = require("slugify");
const AlertSchema = new mongoose.Schema({
parentId: {
type: mongoose.Schema.ObjectId,
required: true,
refPath: "parentModel",
},
parentModel: {
type: String,
required: true,
enum: ["orgs", "clients"],
},
status: { type: String, default: "no-status" },
departments: [{ type: mongoose.Schema.Types.ObjectId, ref: "orgs" }],
createdAt: { type: Date, default: Date.now },
createdByType: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
createdById: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
groups: [{ type: String, default: "unGrouped" }],
stage: [{ type: mongoose.Schema.Types.ObjectId, ref: "stages" }],
children: { type: String },
resource: {
type: String,
match: [
/https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)/,
"Please use a valid URL with HTTP or HTTPS",
],
},
notes: [{ type: mongoose.Schema.Types.ObjectId, ref: "notes" }],
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "comments" }],
priority: { type: String },
assignedTo: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
title: {
type: String,
required: [true, "Please add a title"],
maxlength: [50, "Title cannot be more than 50 characters"],
},
message: {
type: String,
required: [true, "Please add a message"],
maxlength: [500, "Message cannot be more than 500 characters"],
},
slug: String,
});
//create alert slug from the title
AlertSchema.pre("save", function (next) {
console.log("Slugify Ran", this.name);
this.slug = slugify(this.title, { lower: true });
next();
});
module.exports = mongoose.model("Testalert", AlertSchema);
Desired relationships diagram:
I'm trying to make a form-maker with Node.Js and MongoDB but confused about the data structure.
By the way, I created a form.model to store the form structure:
{
title: {
type: String,
required: [true, 'Form must have a title']
},
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
role: Number
}],
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
active: {type: Boolean, default: true},
fields: [{
case_id: String,
label: String,
type: Number, //1:selective, 2:descriptive, 3:range
required: Boolean,
default: {
title: String,
value: Number,
},
placeholder: String,
items:[{
label: String,
value: Number,
}],
range:[{
min: Number,
max: Number,
step: Number,
default: {type: Number, default: 0}
}]
}]
}
and a form.data.model to store the data of forms:
{
form: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Form',
required: true
},
fields_data: {
"case_id": Object //value per case_id
}
}
Is that true? or there is the best practice for that?
If I modify the form fields how control the data about?
Finally, I've created the structure of my form-maker data.
form.model:
{
title: {
type: String,
required: [true, 'Form must have a title']
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: [true, 'Form must have a owner']
},
active: {type: Boolean, default: true},
deleted: {type: Boolean, default: false},
fields: [{
name: String, //that field id and must be auto generated and not be modified by end user
label: String,
type: Number, //1:Selective, 2:Descriptive, 3:Range
required: Boolean,
placeholder: String,
selectable_items:[{
label: String,
value: Number,
selected: Boolean
}],
range:[{
min: Number,
max: Number,
step: Number,
default: {type: Number, default: 0}
}]
}]
}
form.users.model:
{
form: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Form',
required: true
},
users: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
role: Number //0:Admin, 1:Editor, 3:Viewer
}
]
}
form.values.model:
{
form: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Form',
required: true
},
values: [
{
name: String,
value: Object
}
]
}