Why Mongoose default value not applied in existing model? - node.js

I had a mongoose schema like below:
const orderSchema = new Schema({
orderBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
items: { type: Schema.Types.ObjectId, ref: 'cart', required: true },
...
)}
I have added some data in the database using this schema. After a few days I added a new field like below:
prepareTime: { Type: Number, default: 0 }
After adding this field, I updated all the existing documents with value prepareTime:0
Now, when I save a new document, the prepareTime field with default value 0 is not being saved. How to achieve this functionality?

Related

Node mongoose fill createdBy and updatedBy column with userId in every Model save and update

In Node, Mongoose I am trying to achieve something like Laravel's created_by and updated_by columns, these 2 columns are automatically updated by the ORM in every INSERT and UPDATE operation to that particular table.
For example, below is the Material schema, here I want to store the createdBy and updatedBy column with userId whenever any user performs INSERT and UPDATE operations respectively in the materials collection.
I know this can be done while saving the records in particular controller method, but every time in every method I will have to add this and it becomes a pain, so I am looking for a solution where I can define something in the Model itself and it does the job just like the mongoose-delete package.
const mongoose = require('mongoose')
const mongoose_delete = require('mongoose-delete')
const materialSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
type: {
type: String,
required: true,
enum: ['hard', 'soft'],
},
image: {
type: String,
default: null
},
active: {
type: Boolean,
default: true
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
default: null
},
updatedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
default: null
}
}, { timestamps: true })
materialSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, deletedByType: String })
const Material = mongoose.model("Material", materialSchema)
module.exports = Material

infinite population mongoose node js

I have got two models which are ( form, user )
each user has formId field which is the object id of the form object he has
each form has a field called userId which is for the user who has this form
the problem is that I am using mongoose-autopopulate package and if I changed the formId and userId fields to be auto-populated it will open an infinite population with no end
the problem is that some other schemas have a field called formId which is associated with the form object and in this case I want to populate the userId field to get the user info without populating again the formId field.
Schemas Design
const userSchema = new Schema({
name: String,
age: Number,
formId: {
type: Schema.Types.ObjectId,
ref: 'Form',
//this value used to auto populate for mongoose-autopopulate package
autopopulate: true,
},
})
//signing the mongoose-autopopulate plugin
...
//exporting the module
---------------
const formSchema = new Schema({
address: String,
bill: Number,
//the id of the user who added this form
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
//this value used to auto populate for mongoose-autopopulate package
autopopulate: true,
},
})
//signing the mongoose-autopopulate plugin
...
//exporting the module
----------
const orderSchema = new Schema({
products: [],
deliveryBoy: {
type: Schema.Types.ObjectId,
ref: 'Boy',
},
formId: {
type: Schema.Types.ObjectId,
ref: 'Form',
//this value used to auto populate for mongoose-autopopulate package
autopopulate: true,
},
})
//signing the mongoose-autopopulate plugin
...
//exporting the module
Thanks,
Use the maxDepth option mongoose-autopopulate
for example
const orderSchema = new Schema({
products: [],
deliveryBoy: {
type: Schema.Types.ObjectId,
ref: 'Boy',
},
formId: {
type: Schema.Types.ObjectId,
ref: 'Form',
autopopulate: { maxDepth: 2 },
},
})

How can i query the data in a sub-document of a document from a sub-document of another document

This is my category schema. For every category document, there is a subdocument of subcategories
#category schema
const CategorySchema = mongoose.Schema({
name: {
type: String, required: true
},
subcategories: [{
name: {
type: String, required: false
},
}],
created : {
type : Date,
default: Date.now()
}
});
let Categories = mongoose.model('categories', CategorySchema);
# selected category schema
const BusinessCategoriesSchema = mongoose.Schema({
business_id: {
type: String
},
category_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "categories",
required: true
},
subcategories: [{
subcategory_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "subcategories._id",
required: false
}
}]
});
let businessCategories = mongoose.model('business-categories', BusinessCategoriesSchema);
How can I retrieve the subcategories sub-document from Categories schema when I perform a query on business-categories collection?
#This is the code snippet I am using but am not getting my desired result
const query = await businessCategories.find({business_id : businessId })
.populate('category_id')
.populate('subcategories.subcategories_id');
I know I am not doing something right.
I was able to get the category name from categories schema but I could not get the subcategories sub-document from the categories schema.
Thank you in advance

How to set a foreign key in mongoose?

I need to set a field from another collection as a foreign key to my mongoose schema.
I have a counter pid to productSchema. I need to set pid as a foreignkey to orderSchema
const orderSchema = mongoose.Schema({
id: mongoose.Schema.Types.ObjectId,
product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product',
required:
true },
quantity: { type: Number, default: 1 }
});
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
price: { type: Number, required: true },
productImage: { type: String }
});
Well MongoDB is not a relational DB so it does not support concepts like foreign key. In mongoDB you have to structure your data in such a way that you can fetch information easily.
You should see if you can go with Aggregation or something but mongoDB does not have foreign keys. More important you should make correct choice when you are creating a DB , you should select appropriate DB according to your requirements.

Mongoose - store multiple model types in one field

I have a schema which looks like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamps');
const BidSchema = new Schema({
bidder: {
type: Schema.ObjectId,
ref: 'Buyer'
},
counterOffer: {
type: Schema.ObjectId,
ref: 'Counter_Offer'
},
box: {
type: Schema.ObjectId,
ref: 'Box'
},
status: {
type: String,
enum: ['Pending', 'Approved', 'Disapproved']
},
bidPrice: Number,
bidTimeout: {
type: Date,
default: Date.now
},
isAnonymous: Boolean,
});
BidSchema.plugin(timestamps);
module.exports = mongoose.model('Bid', BidSchema);
I want to store multiple data types in the Box field. For example, I have a Box model and also I have a GroupedBox model. I want to be able to store id for both of these schemas and to be able to populate this field accordingly. For instance, if the document will store an ObjectId that references a GroupedBox document, the populate method will fetch the right GroupedBox document. Same goes for a Box document id.
I read about Mixed field types but I don't see how that can help me.
replace box field in your code with this:
box: {
box: { type: Schema.Types.ObjectId, ref: 'Box' },
groupedBox : { type: Schema.Types.ObjectId, ref: 'GroupedBox' }
}
To populate box you need to access box with a dot populate("box.box") similar to groupedBox you populate it this way populate("box.groupedBox")

Resources