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);
});
};
Related
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
I'm using mongoose to to define 2 schemas.
employee.js
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const Role = require("./role");
const employeeSchema = mongoose.Schema({
code: { type: String, required: true, unique: true, index: true },
names: { type: String, required: true },
last_names: { type: String, required: true },
role: Role.schema,
dui: { type: String, required: true, unique: true, index: true },
nit: { type: String, required: false, unique: true, index: true },
sex: { type: String, required: false },
civil_status: { type: String, required: false },
birthday: { type: Date, required: false },
telephone: { type: String, required: true },
city: { type: String, required: true },
address: { type: String, required: true },
active: { type: Boolean, required: true },
});
employeeSchema.plugin(uniqueValidator);
module.exports = mongoose.model("Employee", employeeSchema);
and role.js
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const roleSchema = mongoose.Schema({
code: { type: String, required: true, unique: true, index: true },
description: { type: String, required: true }
});
roleSchema.plugin(uniqueValidator);
module.exports = mongoose.model("Role", roleSchema);
The problem I have is that, whenever I insert a document with a role code that's repeated I get an error because of the unique validation. I have tried deleting
roleSchema.plugin(uniqueValidator);
from role.js and I have also tried using .set to alter the field in role.
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const Role = require("./role");
const subRole = Role.schema.clone().set('code', {unique: false}).set('code', {index : false});
const employeeSchema = mongoose.Schema({
code: { type: String, required: true, unique: true, index: true },
names: { type: String, required: true },
last_names: { type: String, required: true },
role: subRole,
dui: { type: String, required: true, unique: true, index: true },
nit: { type: String, required: false, unique: true, index: true },
sex: { type: String, required: false },
civil_status: { type: String, required: false },
birthday: { type: Date, required: false },
telephone: { type: String, required: true },
city: { type: String, required: true },
address: { type: String, required: true },
active: { type: Boolean, required: true },
});
employeeSchema.plugin(uniqueValidator);
module.exports = mongoose.model("Employee", employeeSchema);
I always get an error saying that role code needs to be unique. Am I using .set incorrectly? or what am I missing? Thank you very much in advance.
Solved it changing:
const subRole = Role.schema.clone().set('code', {unique: false}).set('code', `{index : false});`
to
const subRole = Role.schema.clone().set('excludeIndexes', true);
Deleted the employees's collection so it would recreate it with the right indexes and that did the trick.
It was mentioned in one of mongoose's issues in github:
https://github.com/Automattic/mongoose/issues/11547
Supposedly they implemented something about it but I didn't get it. The above worked for me though.
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
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.
I need to get all docs from service collection and it's showing all records when i console content. In content collection there is field mids which is media id and all images are going to media collection. I need to get media url for specific service. But when i console content.mids it returns undefined .Do i need to change in query?
Code is attached for your reference.
// Controller
services: (req, res) => {
Posts.find({content_type:'service'}).then(function(content) {
console.log(content); //right
console.log(content.m_ids); //showing undefined
Media.findById(content.m_ids).then(media => {
res.render('default/services', {content: content, reqUrl: req.url});
});
})
}
Services Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Schema = new Schema({
content_type: {
type: String,
required: true,
maxlength:20
},
content_title: {
type: String,
required: true,
max:100
},
content_url: {
type: String,
required: true,
maxlength:200
},
content_description: {
type: String,
required: true,
},
content_full_description: {
type: String,
required: false,
},
pt_ids: {
type: String,
required: false,
},
pc_ids: {
type: String,
required: false,
},
m_ids: {
type: String,
required: false,
},
created_by_user_id: {
type: String,
default: 1,
},
created_on: {
type: Date,
default: Date.now
},
updated_on: {
type: Date,
default: Date.now
},
post_icon_svg: {
type: String,
required: false,
}
});
module.exports = {Posts: mongoose.model('content_data', PostsSchema )};
// Media Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MediaSchema = new Schema({
media_name: {
type: String,
required: true
},
media_title: {
type: String,
required: true
},
media_alt: {
type: String,
required: true
},
media_description: {
type: String,
required: false
},
media_url: {
type: String,
required: true,
unique: true
},
created_by_user_id: {
type: String,
default: 1,
},
created_on: {
type: Date,
default: Date.now
},
updated_on: {
type: Date,
default: Date.now
}
});
module.exports = {Media: mongoose.model('media', MediaSchema )};