mongoose schema not sending correct address details - node.js

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

Related

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

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.

MongoDB schema validation with nested array or object in strict mode

i have schema which is nested
so need to validate whole schema, like if it has an extra attributes then throw error
i have tried with strict: 'throw' but that work only for main attributes, not for nested attributes.
const { Schema } = mongoose;
const DatasourceSchema = new Schema({
id: {
type: String,
unique: true,
required: true,
},
display_name: {
type: String,
required: true,
maxlength: 125
},
contact_info: {
type: Schema({
website: {
type: String,
required: false
},
registrar_phone: { type: String },
registrar_email: { type: String },
addresses: [{
type: Schema({
addr1: { type: String, required: false },
addr2: { type: String, required: false },
country: {
name: { type: String, required: true },
a2_code: { type: String, required: true },
}
}),
required: false
}]
}),
required: true,
}
},
{
strict: 'throw',
useNestedStrict: true
});
what i need is if i add any extra KEY (attributes) in object or array at any level that will throw errors

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

Mongoose: How to populate across multiple levels and use field selection in the same time?

I have succesfully used population across multiple levels and field selection separately. But I couldn't find a way to do them both at the same time.
Population across multiple levels
Profile.findOne({ user: req.user.id })
.populate({
path: "user",
populate: { path: "following" },
})
Field selection:
Profile.findOne({ user: req.user.id })
.populate("user", ["name", "avatar"])
I want to do something like this:
NOTE: THIS DOESN'T WORK
Profile.findOne({ user: req.user.id })
.populate({
path: ["user", ["name", "avatar"]],
populate: { path: "following" },
This is the Profile model:
const ProfileSchema = new Schema({
//We want to associate the user with the profile
user: {
//This will associate the user by his id
type: Schema.Types.ObjectId,
ref: "users",
},
// We want a user friendly url
handle: {
type: String,
// required: true, // Even though we are doing pre-validatioon
max: 40,
},
bio: {
type: String,
},
school: {
type: String,
},
major: {
type: String,
},
website: {
type: String,
},
location: {
type: String,
},
// Optional (might add it later)
/**
* status: {
//where they are in their career
type: String,
required: true
},
*/
skills: {
// In the form they will put skill1,skill2,.. and we will turn that into an array
type: [String],
// required: true,
},
interests: {
// In the form they will put interest1,interest2,.. and we will turn that into an array
type: [String],
// required: true,
},
help_offers: {
// In the form they will put help_offer1,help_offer2,.. and we will turn that into an array
type: [String],
// required: true,
},
// Might be volunteering experience
experience: [
{
title: { type: String, required: true },
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
// Not required, going to be a checkbox
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
education: [
{
school: { type: String, required: true },
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
// Not required, going to be a checkbox
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
facebook: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
dafault: Date.now,
},
videoURL: {
type: String,
},
});
This is the User model:
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
avatar: {
type: String,
},
birthday: {
type: String,
required: true,
},
country: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
following: [
{
type: Schema.Types.ObjectId,
//The User has only ObjectId in uses array. ref helps us get full fields of User when we call populate() method.
//https://bezkoder.com/mongodb-many-to-many-mongoose/
ref: "users",
},
],
followers: [
{
type: Schema.Types.ObjectId,
ref: "users",
},
],
});
I am not sure if I understood your aim by this
Profile.findOne({ user: req.user.id })
.populate({
path: ["user", ["name", "avatar"]],
populate: { path: "following" },
But if what i understood is what you want, then we're lucky. here is what i got.
await RequestAproves.find()
.populate('user', 'firstName surname email roleId')
.populate({
path: 'request',
populate: [
{ path: 'budgetItem', select: 'code name' },
{ path: 'user', select: 'firstName surname' },
],
}
)
More details will come later, Sorry, I couldnt use your schema description, Incase it doesnt work out, let me know, ill try to use your schema.

The opeartor set doesn't work in mongodb. Or any other methods to add a new field into the document?

The operator $set can't add a new field hide. I thought, I was doing everything according to the mongodb official documentation. Can somebody tall me what I'm doing wrong. Thanks
createClass
.updateMany(
{ classname: req.body.className },
{ $set : {"hide":true}},
{ multi: true, upsert: false },
)
Here is the schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Classes = new Schema({
classname: {
type: String,
required: true,
},
Subject: {
type: String,
required: true,
},
Chapter: {
type: String,
required: true,
},
Topic: {
type: String,
required: true,
},
SubjectimgPath: {
type: String,
},
ChapterimgPath: {
type: String,
},
TopicimgPath: {
type: String,
},
content: {
type: Array,
}
});
Classes.index({ "$**": "text" });
const Createclass = mongoose.model("AllClasses", Classes);
module.exports = Createclass;
Try this :
const Classes = new Schema({
classname: {
type: String,
required: true,
},
Subject: {
type: String,
required: true,
},
Chapter: {
type: String,
required: true,
},
Topic: {
type: String,
required: true,
},
SubjectimgPath: {
type: String,
},
ChapterimgPath: {
type: String,
},
TopicimgPath: {
type: String,
},
content: {
type: Array,
}
}, {strict :false} );

Resources