Cannot populate when I use Foreign key in mongoose - node.js

I tried to join three documents in mongodb using mongoose in nodejs, but unfortunately this error occurs. My mongoose version is 6.2.3
Declaring Schema
const mongoose = require('mongoose')
const declaringSchema = mongoose.Schema({
cniDeclaring: { type: Number, required: true },
father: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Father',
required: true,
},
mother: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Mother',
required: true,
},
name: { type: String, required: true },
surname: { type: String, required: true },
birthDay: { type: Date, required: true },
birthPlace: { type: String, required: true },
gender: { type: String, required: true },
address: { type: String, required: true },
relationShipDeclared: { type: String, required: true },
phone: { type: Number, required: true },
request: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Request',
}],
});
module.exports = mongoose.model('Declaring', declaringSchema);
Declared Schema
const mongoose = require('mongoose')
const declaredSchema = mongoose.Schema({
name: { type: String, required: true },
surname: { type: String, required: true },
father: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Father',
},
mother: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Mother',
},
birthDay: { type: Date, required: true },
birthPlace: { type: String, required: true },
gender: { type: String, required: true },
nationality: { type: String, required: true },
request: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Request',
},
});
module.exports = mongoose.model('Declared', declaredSchema);
Father Schema
const mongoose = require('mongoose')
const fatherSchema = mongoose.Schema({
cniFather: { type: Number, required: true },
nameP: { type: String, required: true },
surname: { type: String, required: true },
birthDay: { type: Date, required: true },
birthPlace: { type: String, required: true },
address: { type: String, required: true },
phone: { type: Number, required: true },
occupation: { type: String, required: true },
declaring: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Declaring',
}],
declared: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Declared',
}],
});
module.exports = mongoose.model('Father', fatherSchema);
Now I want to get all the fathers back
const Father = require('../models/Father');
exports.createFather = (req, res, next) => {
const father = new Father({
...req.body
});
father.save()
.then(() => res.status(201).json({ message: 'Father created !'}))
.catch(error => res.status(400).json({ error })
);
}
exports.getAllFathers = (req, res, next) => {
Father.find()
.populate('declarings')
.populate('declareds')
.exec((err, res) => {
if(err){
console.log(err);
}
});
};
and I have the following error:
MongooseError: Cannot populate path declarings because it is not in your schema. Set the strictPopulate option to false to override.

Related

How to update a specific object in a array of objects by Item ID in Node.js and Mongoose

I need a code in Express.Js and Mongodb where I can change an exact string inside an object through the id of the item, I need to change the string "colorSelected" to a new value, changing only what I put in the body, in my previous failed attempts every change I made would change the entire object, I don't want that, thank you in advance.
Router Cart.js
//update color cart
router.patch("/cart/:id", Auth, async (req, res) => {
});
Model Cart.js
const mongoose = require('mongoose')
const ObjectID = mongoose.Schema.Types.ObjectId
const cartSchema = new mongoose.Schema({
owner : {
type: ObjectID,
required: true,
ref: 'User'
},
items: [{
itemId: {
type: ObjectID,
ref: 'Item',
required: true
},
img: String,
name: String,
colorSelected: String,
colors: Array,
stock: Number,
quantity: {
type: Number,
required: true,
min: 1,
default: 1
},
price: Number
}],
bill: {
type: Number,
required: true,
default: 0
}
}, {
timestamps: true
})
const Cart = mongoose.model('Cart', cartSchema)
module.exports = Cart
Model Item.js
const mongoose = require('mongoose')
const ObjectID = mongoose.Schema.Types.ObjectId
const reviewSchema = mongoose.Schema(
{
name: { type: String, required: true },
rating: { type: Number, required: true },
comment: { type: String, required: true },
user: {
type: ObjectID,
required: true,
ref: 'User'
},
},
{
timestamps: true,
}
)
const itemSchema = new mongoose.Schema({
images: [{
name: {
type: String,
required: true
},
src: {
type: String,
required: true
},
color: {
type: String,
required: true
},
}],
owner : {
type: ObjectID,
required: true,
ref: 'User'
},
name: {
type: String,
required: true,
trim: true
},
description: {
type: String,
required: true
},
category: {
type: Number,
required: true
},
price: {
type: Number,
required: true
},
stock: {
type: Number,
required: true
},
visibility: {
type: Boolean,
required: true
},
reviews: [reviewSchema],
rating: {
type: Number,
required: true,
default: 0,
},
numReviews: {
type: Number,
required: true,
default: 0,
}
}, {
timestamps: true
})
const Item = mongoose.model('Item', itemSchema)
module.exports = Item

What is the correct way to enter an Array?

I want to enter data via Postman into an array form using id Collection in the database also how can I write a valid JSON script for the modal for the modal
Add data using id Collection
controller
const addAcademicExperience = async (req, res, next) => {
//const id = req.params.id;
const {AcademicExperience} = req.body;
let academicexperience;
try {
academicexperience = await AcademicExperience.findByIdAndadd(id, {
AcademicExperience
});
await academicexperience.save();
} catch (err) {
console.log(err);
}
if (!academicexperience) {
return res.status(404).json({ message: 'Unable to Add' })
}
return res.status(200).json({academicexperience});
model Schema
Some data is required in an array and some are not
per user per user
To clarify, the site is similar to LinkedIn
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const FacultySchema = new Schema({
Faculty_ID: {
type: Number,
required: true,
unique: true,
},
Name: {
type: String,
required: true,
},
Phone_Number: {
type: String,
required: true,
},
Email: {
type: String,
required: true,
},
AcademicExperience: [{
institution: { type: String, required: true },
rank: { type: String, required: true },
title: { type: String, required: true },
working: { type: Boolean, required: true },
}
],
Certifications:
{
type: String,
require: true,
},
Currentm_embership:
{
type: String,
require: true,
},
Servicea_ctivites:
{
type: String,
require: true,
},
Professional:
{
type: String,
require: true,
},
Education:[ {
degree: { type: String, required: true },
discpilne: { type: String, required: true },
institution: { type: String, required: true },
year: { type: Date, required: true },
}
],
Non_academic_experines:[
{
Company: { type: String, required: true },
title: { type: String, required: true },
working: { type: Boolean, required: true },
Description_of_position: { type: String, required: true },
}
],
Honoers_and_awards:
{
type: String,
require: true,
},
Puplications_and_presentation:
{
type: String,
require: true,
},
});
module.exports = mongoose.model("Faculty", FacultySchema);

Mongoose Query is not fetching match data from multiple table

I am using nodejs,mongodb and mongoose. This query is not fetching match data from user and order table. I have read mongoose docs and alot of other articeles. It's according to it but doesn't fetch match data from tables.
Query code:
const data = await order
.find({ admin_id: req.params.id })
.populate("orderRelate");
console.log(data);
My user and order schema code is:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
mobile_no: { type: Number, required: true },
profilePic: { type: String, defaut: "" },
owner: { type: Boolean, defaut: false },
},
{ timestamps: true }
);
const orderSchema = new mongoose.Schema(
{
customer_id: { type: String, required: true },
admin_id: { type: String, required: true },
order_type: { type: String, defaut: "normal" },
order_status: { type: String, required: true },
order_price: { type: Number, required: true },
order_address: { type: String, required: true },
order_pickDate: { type: String, required: true },
order_pickTime: { type: String, required: true },
orderRelate: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
module.exports = mongoose.model("Order", orderSchema);
Please let me know if anyone know why I am facing this issue.
Thanks
Please try with findById maybe it's work
i don't know how you wrote your middleware function but..
await Order.find({orderRelate: req.user.id})

Creating Two Foreign key mongoose inside a controller

Hi I want to implement this snippet of my class diagram using mongoose.
Here is my logic model in detail:
Here is the definition of my Mother model:
const mongoose = require('mongoose')
const motherSchema = mongoose.Schema({
cniMother: { type: Number, required: true },
name: { type: String, required: true },
surname: { type: String, required: true },
birthDay: { type: Date, required: true },
birthPlace: { type: String, required: true },
address: { type: String, required: true },
phone: { type: Number, required: true },
occupation: { type: String, required: true },
});
module.exports = mongoose.model('Mother', motherSchema);
Here is the definition of my Declared model:
const mongoose = require('mongoose')
const declaredSchema = mongoose.Schema({
name: { type: String, required: true },
surname: { type: String, required: true },
father: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Father',
//required: true,
},
mother: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Mother',
//required: true,
},
birthDay: { type: Date, required: true },
birthPlace: { type: String, required: true },
gender: { type: String, required: true },
nationality: { type: String, required: true }
});
module.exports = mongoose.model('Declared', declaredSchema);
I want to retrieve the name of the father and the mother corresponding to the declared.
Can anyone help me please?

nodejs mongoose : cyclic dependency detected

I'm getting a cyclic dependency exception whereas I don't find any cyclic possibility in the very simple code at this point. I'm expecting it is happening due to population between two mongoose models but as said here : mongoose - possible circular dependency? this shouldn't produce this kind of error so I don't understand.
model\customer.js
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var customerSchema = new Schema({
_siretCustomer:
{ type: String, required: true, minlength: 15, maxlength: 15, index: {unique: true} },
fileNumberCustomer:
{ type: String, required: true, minlength: 6, maxlength: 6 },
companyTypeCustomer:
{ type: String, required: true },
companyNameCustomer:
{ type: String, required: true },
contactName1Customer:
{ type: String, required: false, default: null },
contactName2Customer:
{ type: String, required: false, default: null },
landlineContact1Customer:
{ type: String, required: false, default: null },
landlineContact2Customer:
{ type: String, required: false, default: null },
emailContactCustomer:
{ type: String, required: false, default: null },
obligationCommentCustomer:
{ type: String, required: false, default: null },
taskCommentCustomer:
{ type: String, required: false, default: null },
creationDateCustomer:
{ type: Date, default: Date.now },
userCustomer:
[{ type: Schema.Types.ObjectId, ref: 'User', required: true }]
}, { collection: 'customer' });
module.exports = mongoose.model('Customer', customerSchema, 'customer');`
model\user.js
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var userSchema = new Schema({
_trigramUser:
{ type: String, required: true, index: { unique: true } },
lastnameUser:
{ type: String, required: true },
firstnameUser:
{ type: String, required: true },
privilegeUser:
{ type: String, required: true, enum: ['Accountant', 'Social operator'] },
dateCreationUser:
{ type: Date, default: Date.now },
passwordUser:
{ type: String, required: true },
customersUser:
[{ type: String, ref: 'Customer'}]
}, { collection: 'user'});
module.exports = mongoose.model('User', userSchema, 'user');
controller\session\customerController.js
exports.readCustomer = (req, res) => {
database.getConnection();
customer.find(req).populate('userCustomer').exec((err, customer) => {
if (err) return res.status(500).json(err.stack);
res.status(200).json(customer);
});
};

Resources