How to save nested array of objects data using mongoose? - arrays

So, I'm sending data from angular reactive form like:
Angular reactive form UI image
and
Data being sent to backend in browser console image
I have made schema for task as:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let taskSchema = new Schema({
taskId:{
type:String,
unique:true
},
task:{
type:String,
default:''
},
subTask:[{
type: Schema.Types.ObjectId,
ref: 'SubTask'
}]
}
module.exports = mongoose.model('Task',taskSchema);
Schema for Sub-Task as:
let subTaskSchema = new Schema({
title:String,
subSubTask:[{
type: Schema.Types.ObjectId,
ref: 'SubSubTask'
}]
})
module.exports = mongoose.model('SubTask',subTaskSchema);
Schema for Sub-Sub-Task as:
let subSubTaskSchema = new Schema({
title:String
})
module.exports = mongoose.model('SubSubTask',subSubTaskSchema);
Now,I'm confused about how to save nested array of objects data in mongodb using mongoose?

you can define your schema like this
const userSchema = new mongoose.Schema({
likedBooks: [{
type: mongoose.Types.ObjectId,
ref: 'books'
}],
email: {
type: String,
required: true
},
name: {
type: String,
required: true
}
});
exports.User = mongoose.model('users', userSchema);
then you can populate data by doing
user = User.find({ email: req.body.email }).populate('likedBooks');
here likedBooks contains _id of each book
const bookSchema = new mongoose.Schema({
isbn: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
author: {
type: String,
required: true
},
publisher: {
type: String,
default: ""
},
imageUrl: {
type: String,
required: true
},
description: {
type: String,
default: ""
}
});
exports.Book = mongoose.model('books', bookSchema);
for both schema i have not put _id as it is auto generated by mongodb and it is used as reference

The Object Model should look like this before saving.
{
taskId: 1,
task: 'Do something',
subTask: [{
title: 'Write a essay',
subSubTask: [{
title: 'Collect details to write an essay'
}]
}]
}
Hope it helps...

Related

MissingSchemaError: Schema hasn't been registered for model "[object Object]". Use mongoose.model(name, schema) at Mongoose.model

Missing Schema Error: Schema hasn't been registered for model "[object Object]".
Use mongoose model(name, schema)
at Mongoose model
error occurred
need solution for this problem
in ./src/models/channel.js file:
const { Schema, model } = require("mongoose");
// Discord' channel model
const channelSchema = new Schema({
identifier: { type: String, required: true },
message: { type: String, default: "ping !" },
guild: { type: String, required: true },
type: { type: String, required: true },
mode: { type: Boolean }
});
module.exports = model("Channel", channelSchema);
in other files:
const Channel = require("../models/channel");
const toto = await Channel.create({
identifier: 1,
guild: "toto",
type: "tata",
});
console.log(toto);
const mongoose=require('mongoose')
var Schema = mongoose.Schema
const productSchema=new Schema({
name:{
type:String,
required:[true, "please enter product name"]
},
description:{
type: String,
required:[true, "please enter product Description"]
},
created At:{
type: Date,
default: Date. now
}
})
module. exports=mongoose. model("product", product Schema)
After Mongoose. model() put model Name and then Schema
hoping you Got The Solution

How can I insert mongo changes in the deploy website?

My website is running allright and it's connected with Database.
I had to add more informations in my Mongo's collection. (I created the ActionPlanSchema).
import mongoose from "mongoose";
import mongoose_delete from "mongoose-delete";
const VerificationSchema = new mongoose.Schema({
text: { type: String, required: true },
});
const ActionPlanSchema = new mongoose.Schema({
title: { type: String, required: true },
mouraTitle: { type: String, required: true },
text: { type: String, required: true },
});
const RequirementSchema = new mongoose.Schema({
itemNumber: { type: String, required: true },
normPart: {
type: mongoose.Schema.Types.ObjectId,
ref: "NormPart",
required: true,
},
generalRequirement: {
type: mongoose.Schema.Types.ObjectId,
ref: "GeneralRequirement",
required: true,
},
specificRequirementDescription: { type: String, required: true },
subject: { type: mongoose.Schema.Types.ObjectId, ref: "Subject" },
criterion: String,
verification: [VerificationSchema],
actionPlan: [ActionPlanSchema],
});
RequirementSchema.index({ itemNumber: 1, normPart: 1 });
RequirementSchema.index({ specificRequirementDescription: 1 });
RequirementSchema.plugin(mongoose_delete, {
overrideMethods: "all",
deletedAt: true,
deletedBy: true,
indexFields: ["deleted"],
});
export default RequirementSchema;
And using a router in Postman (PUT method), I added some information to the Database ActionPlanSchema. Looking like that:
In my localhost, the actionPlan information it's showing. But when I do the deploy, the actionPlan gets undefined.
I believe that it's because the informations that I added in Postman weren't sent to the database used on the Deploy App.
How can I solve this problem? (I don't know if I could be very clear about my issue)
Anyway, thanks so much!

Why is my mongoose populate query throwing "Cannot populate path because it is not in your schema" error?

I'm building a form management program but right now I'm just trying to build a queue system to handle all the forms when they're assigned to someone.
when I call this first function, it should populate the elements of the activeWork array by pulling from each collection that the entries reference, there are several collections that could be referenced in active work, so I'm trying to use the collection type field to determine what collection to pull from, I don't know if I formatted any of this correctly because its my first time building any of this.
import statesPersons from "./statesPersons.schema.js";
export async function getStatesPersonsActiveWorkByProfileId(req, res){
try{
const { profileId } = req.params
const data = await statesPersons.find({profileId})
.populate('statesPersons.activeWork.referenceId')
return res.send({
message: "success",
data: data,
status: 200 })
}catch(e) {
console.error(e.message)
return res.send({
message: "couldn't fetch active work",
data: null,
status: 500 })
}
}
Here is the schema for statesPersons, the collection where active work is stored.
import mongoose, {model, Schema} from "mongoose";
const activeWorkSchema = new Schema({
active: Boolean,
collectionType: {
type: String,
enum: ['messages'],
},
referenceId: {
type: Schema.Types.ObjectId,
refPath: "statesPersons.activeWork.collectionType"
},
sentBy: {
type: Schema.Types.String,
ref: "statesPerson",
},
sentTo: {
type: Schema.Types.String,
ref: "statesPerson",
},
timeRecived: Date,
dueDate: Date,
subject: String,
viewed: Boolean,
content: {},
})
const statesPersonsSchema = new Schema({
profileId:{
type: String,
required: true,
unique: true
},
department: {
type: String,
required: true,
index: true,
},
firstName: String,
lastName: String,
location: String,
org: String,
title: String,
jobDescription: String,
email: {
type: String,
lowercase: true,
},
phoneNumber: String,
activeWork: [activeWorkSchema],
emailList: [String],
jobAssignments: [String],
affiantInfo: {
affiantInfoTitle: String,
affiantInfoExperience: String,
},
assessments: [
{
assessdBy: {
type: Schema.Types.ObjectId,
ref: "statesPerson",
},
dueDate: Date,
questions: {},
},
],
});
export default mongoose.model("statesPersons", statesPersonsSchema);
When I make a query, I get:
Cannot populate path statesPersons.activeWork.referenceId because it is not in your schema. Set the strictPopulate option to false to override.
I don't know if I formatted my populate correctly or if the problem is in my schema,

Mongose array inside of array

I want to achieve like this:
On every user there's subject, and on every subject there's students.
user: [{ subjects: {subjectCode, description},[{students: {name, year, phone}}]}]
I already got the users -> subject side.
my problem now is how can i achieve to create students inside of subjects?
This is for my authentication.
User.js
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('user', UserSchema);
Every user can create subjects.
Subject.js
const mongoose = require('mongoose');
const SubjectSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
student: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'student',
},
],
title: {
type: String,
required: true,
},
description: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('subject', SubjectSchema);
In every subjects, there's should array of students.
Student.js
const mongoose = require('mongoose');
const StudentSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
name: {
type: String,
required: true,
},
year: {
type: String,
},
phone: {
type: String,
},
email: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('student', StudentSchema);

Mongoose query in MEAN stack

I've installed the MEAN stack using the yeoman generator and I would like to implement a query that returns true if a document with a given value for a specific property exists.
It this is the model:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var FirstSchema = new Schema({
field1: {
type: Number,
trim: true,
default: ''
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
});
var SecondSchema = new Schema({
field1: {
type: Number,
trim: true,
default: ''
},
field2: {
type: String,
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
});
mongoose.model('First', FirstSchema);
mongoose.model('Second', SecondSchema);
During the creation of Second objects, I assign the $scope.field2 = $stateParams.firstId;
The given query generated by yeoman in the client side is:
$scope.find = function() {
$scope.firsts = Firsts.query();
};
How query if First._id == Second.field2?

Resources