Mongoose: How can I reference a nested schema that is in a separate file? - mongodb

If two schemas are in the same file, you can reference it with: [AccountSchema]. You can see that in the "accounts" property of the UserSchema.
import express from 'express'
import mongoose from 'mongoose'
const Schema = mongoose.Schema
import Account from './accounts'
let AccountSchema = new Schema ({
accountName: {
type: String,
trim: true,
required: true,
unique: [true, "You already have an account with this name."],
},
percent: {
type: Number,
min: 1,
max: 100,
required: true
},
isGoal: {
type: Boolean,
default: false
},
accountHistory: {
type: Array
}
})
let UserSchema = new Schema ({
username: {
type: String,
unique: [true, "This username is taken."],
trim: true,
},
email: {
type: String,
unique: [true, "This email is already being used."],
trim: true
},
password: {
type: String,
trim: true
},
infusions: {
type: Array,
timestamps: true
},
accounts: {
type: [AccountSchema],
count: {
type: Number,
default: 8
}
},
secretToken: {
type: String
},
active: {
type: Boolean,
default: false
},
isAdmin: {
type: Boolean,
default: false
}
}, {
timestamps: true,
})
const User = mongoose.model('users', UserSchema)
export default User
But what do you do if the schemas are in separate files? How can you reference them? I tried like this, but it didn't work:
// account.js
import express from 'express'
import mongoose from 'mongoose'
const Schema = mongoose.Schema
let AccountSchema = new Schema ({
accountName: {
type: String,
trim: true,
required: true,
unique: [true, "You already have an account with this name."],
},
percent: {
type: Number,
min: 1,
max: 100,
required: true
},
isGoal: {
type: Boolean,
default: false
},
accountHistory: {
type: Array
}
})
const Account = mongoose.model('users', AccountSchema)
export default Account
And the User schema in a separate file with:
// users.js
import express from 'express'
import mongoose from 'mongoose'
const Schema = mongoose.Schema
import Account from './accounts'
let UserSchema = new Schema ({
username: {
type: String,
unique: [true, "This username is taken."],
trim: true,
},
email: {
type: String,
unique: [true, "This email is already being used."],
trim: true
},
password: {
type: String,
trim: true
},
infusions: {
type: Array,
timestamps: true
},
accounts: {
type: [Account],
count: {
type: Number,
default: 8
}
},
secretToken: {
type: String
},
active: {
type: Boolean,
default: false
},
isAdmin: {
type: Boolean,
default: false
}
}, {
timestamps: true,
})
const User = mongoose.model('users', UserSchema)
export default User
In one article I was told to export the schema, not the model that references the schema, but they did not give any idea as to how to achieve that.

Try removing below line from your account.js file
const Account = mongoose.model('users', AccountSchema);
And change the last line to this
export default AccountSchema;

Related

mongoose validator not working as expected

i want to add batch,department,stream,id fields to the schema depending if usertype is “Student”,i do not understand why,but sometimes it adds the fields sometimes not.forexample if i created a user with usertype “Student” first it does not add the fields,but after that when i created a user with usertype “Teacher” or “Admin” it asks me the fields are required meaning it add the fields and this happens vice versa.why any way to fix this issue?please help guys.
what i have tried well,i have asked chatGpt but no answers i mean just the answers do not solve the issue.
here is the code
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
fullName: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
userType: {
type: String,
required: true,
},
phoneNumber: { type: String, required: true },
password: { type: String, required: true },
approved: { type: Boolean, default: true },
},
{
timestamps: true,
}
);
userSchema.pre("validate", function (next) {
if (this.userType === "Student") {
this.constructor.schema.add({
batch: {
type: Number,
required: true,
},
department: {
type: String,
required: true,
},
stream: {
type: String,
required: true,
},
id: { type: String, required: true }, //, unique: true
});
}
next();
});
const userModel = mongoose.model("users", userSchema);
module.exports = userModel;

Populate a property of a mongoose schema with all the data in another collection

I have a model with articles, and would like to populate an array of data with all the documents in a collection.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ArticlesSchema = new mongoose.Schema({
path: {
type: String,
required: true,
unique: true,
},
base_headline: {
type: String,
required: true,
},
intro: {
type: String,
required: true,
},
featured_image: {
type: String,
required: true,
},
author: {
type: String,
required: true,
},
platform_filter: {
type: String,
},
free_filter: {
type: String,
},
content_type: {
type: String,
required: true,
},
data: [{ type: Schema.Types.ObjectId, ref: 'DesignProducts' }],
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('Articles', ArticlesSchema);
The data property should be populated with all documents in the DesignProducts collection.
I tried running this but the data array is still empty:
Article.findOne({ path: slug }).populate('data').exec();
Here is what the designProducts model looks like:
const mongoose = require('mongoose');
const DesignProductsSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
intro: {
type: String,
required: true,
},
website: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('DesignProducts', DesignProductsSchema);
This array should be populated with all the documents in the DesignProducts collection:

MongoDB gives duplicated error when I use the same name that is unique: false

I try to save and update an entry with upsert, checking the unicity (is that the word? uniqueness?), of my own id key, called id. However, when I create a new entry, with a new id, if I write the same name for the object, the error happens:
errmsg: 'E11000 duplicate key error collection:
app.ticket index: nombre_1 dup key: { nombre: "James
Bond" }', [Symbol(mongoErrorContextSymbol)]: {}
The controller looks like this:
exports.guardarParte = (req,res,next) =>{
const newParte = {
id: req.body.id,
nombre: req.body.nombre,
telefono: req.body.telefono,
ref: req.body.ref,
marca: req.body.marca,
fecha: req.body.fecha,
averia: req.body.averia
}
parte.updateOne({id:newParte.id},{$set:newParte}, {upsert:true}, (err,parte)=>{
if(err && err.code === 11000){
return res.status(409).send("El parte ya existe(?)"+err);
}
if(err){
return res.status(500).send("No se ha podido crear el parte");
}
res.send(parte);
})
}
The model looks like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.set('useCreateIndex',true);
mongoose.set('useUnifiedTopology',true);
const reparacionSchema = new Schema({
id: {
type: String,
required: false,
trim: true,
unique: true
},
nombre: {
type: String,
required: false,
trim: true,
unique: false
},
telefono: {
type: Number,
required: false,
trim: false
},
ref: {
type: String,
required: false,
trim: false
},
marca: {
type: String,
required: false,
trim: false
},
fecha: {
type: Date,
required: false,
trim: false
},
averia: {
type: String,
required: false,
trim: false
},
},{
timestamps: true
});
module.exports = reparacionSchema;
As you see in the model, nombre is set as unique:false. knowing this, I don't get why the error.

How to store range(in geocircle radius form) in mongoose schema

I am building an e-commerce application. Every store has a delivery range so i want to set delivery range of every store in the database to show the store only to those who falls in the delivery range.
Store Schema.
const mongoose = require("mongoose");
const sellerSchema = new mongoose.Schema({
name:{
type: String,
required: true,
},
type: {
type: String,
required: true
},
location: {
type: {
type: "String",
enum:['Point']
},
coordinates: {
type: [Number],
index: '2dsphere'
}
},
owner: {
type: String,
required: true
},
items: [{
type: mongoose.Schema.Types.ObjectId,
ref: "items"
}],
contact: {
type: String,
required: true
},
loginId: {
index:true,
unique: true,
type: String,
},
password: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});
const sellerModel = mongoose.model("sellers",sellerSchema);
module.exports = sellerModel;

Data is not inserted as per schema

I had defined mongoose schema and i tried to insert data into mongodb.But it is not inserted as per defined schema
export const EmpSchema: mongoose.Schema = new Schema({
name: {
type: String,
required: true
},
empNo: {
type: String,
required: true
},
skill: {
type: [String],
required: true
},
address: {
type: String,
required: true
}
}, {
_id: false,
versionKey: false,
retainKeyOrder: true
});
It is getting stored like Array elements as last field.like
name
empno
address
skill
export const EmpSchema: mongoose.Schema = new Schema({
name: {
type: String,
required: true
},
empNo: {
type: String,
required: true
},
skill: {
type: [String],
required: true
},
address: {
type: String,
required: true
}
}, {
_id: false,
versionKey: false,
retainKeyOrder: true
});
YOUR SCHEMA DEFINATION IS CORRECT PLEASE CHECK THE CONTROLLER PART WHERE YOU PUT THE INSERT QUERY . THERE MATTERS A INSERTION ORDER