This is my Product table schema
let schema = new mongoose.Schema({
title: {type: String, required: true},
price: {type: Number, required: true},
description: {type: String, required: true},
sizes: {type: Object, required: true},
offer: {type: Number, default: 0},
images: {type: Array, required: true},
deal: {type: Boolean, default: false},
category: {
_id: {type: Schema.Types.ObjectId, required: true},
name: {type: String, required: true}
},
company_name: {type: String, required: true}
});
What I am trying to do
I am trying to validate if category.name value equal exist in my another table called Category.
You could use an async validator and query the categories collection. Something like this (using promise sytax for validator):
let schema = new mongoose.Schema({
title: {type: String, required: true},
price: {type: Number, required: true},
description: {type: String, required: true},
sizes: {type: Object, required: true},
offer: {type: Number, default: 0},
images: {type: Array, required: true},
deal: {type: Boolean, default: false},
category: {
_id: {type: Schema.Types.ObjectId, required: true},
name: {
type: String,
required: true,
validate: function(nameVal) {
return new Promise(function(resolve, reject) {
let Category = mongoose.model('Category'); //you would have to be sure that Category model is loaded before this one. One reason not to do this
Category.findOne({name: nameVal}, (err, cat) => resolve(cat ? true : false)); //any non null value means the category was in the categories collection
});
}
}
},
company_name: {type: String, required: true}
});
Some thoughts about this:
This is documented at http://mongoosejs.com/docs/validation.html#async-custom-validators.
As it states there, the validator is not run by default on updates. There are a lot of caveats to read through there.
In my experience with NoSQL DBs, the code creating a new Product would take care to make sure the category being assigned was valid. The code probably found the category from the DB at some point prior. So having a validator lookup would be redundant. But you may have a situation where you have a lot of code that creates Products and want validation in one place.
When I see that you are storing a document of {_id: ..., name: ...} as the category field in your Product schema, I think you might want this instead:
...
category: {Schema.Types.ObjectId, ref: 'Category'},
This allows you to store a reference to a category you have retrieved from the categories collection. Mongoose will load up the category document inline for you when you retrieve the products, if you use the populate method on your query. See http://mongoosejs.com/docs/populate.html. There are a lot of options with the populate functionality you might find useful. It does not do validation that the category is valid on save, as far as I know. But if you take this approach, you would have already looked up the category previously in the code before your save (see the link to get a better idea what I mean). Essentially this gives you join like behavior with MongoDB, with the storage savings and other benefits one expects from "normalization".
Related
Let say I have a large Model like this:
const largeSchema = mongoose.Schema({
var1: {type: Number, required: true, unique: true},
var2: {type: String, required: true},
var3: {type: String, required: true},
var4: {type: String, required: true},
varsA: {type: [String], required: true, default: []},
varsB: {type: [SchemaB], ref: 'SchemaB'},
var5: {type: mongoose.Schema.Types.ObjectId, ref: 'Schema5'},
varsC: {type: [SchemaC], required: true, default: []},
varsD: {type: [SchemaD], required: true, default: []},
varsE: {type: [SchemaE], required: true, default: []},
varsF: {type: [SchemaF], required: true, default: []},
var6 {type: Schema6},
varsG: {type: [SchemaG], required: true, default: []},
varsH: {type: [SchemaH], required: true, default: []},
},{timestamps: true});
As you can see, model like this one contains each referenced and embedded models, some in array some not. Furthermore some of these array can be large (no more than 100 items per arrays).
My question is about these embedded schemas in array.
Let's say that every fields can be updated. If I want to update one item in varsE. Should I use a Global PATCH that will patch my whole list; or build one route for each array of this model?
Architecture: Node.JS - Express - Mongoose
I would suggest you update only the specific element in the array instead of a global patch in order to avoid unnecessary contamination of other elements.
Following is an example of how you could update a specific element in the array.
await LargeSchemaModel.update({'items.id': 1}, {'$set': {
'items.$.name': 'updated name',
'items.$.value': 'updated value'
}});
I have two schemas (Portfolio and Projects that relate to portfolios):
portfolioSchema = new Schema({
name: {type: String, required: true, unique: true},
isActive: {type: Boolean, default: true}
});
projectSchema = new Schema({
name: {type: String, required: true, unique: true},
isActive: {type: Boolean, required: true, default: true},
portfolio: {type: mongoose.Schema.Types.ObjectId, ref: 'portfolioSchema', required: true},
isCodeBaseFullyOwned: {type: Boolean, required: true, default: false}
});
Is there a way to select all portfolios and 'populate' their relevant projects? I can group projects by portfolio but then if there are no projects in a portfolio I would have to figure a way to additionally pull this information, too.
There are 2 ways you could do this.
One would be adding an array of projectIds on the portfolio which you could then populate but could become messy if you are not careful with cleaning up/managing references on updates.
This can be done by updating the portfolioSchema to
portfolioSchema = new Schema({
name: {type: String, required: true, unique: true},
isActive: {type: Boolean, default: true},
projects: [{type: mongoose.Schema.Types.ObjectId, ref: 'projectSchema', required: true}]
});
The other option would require grouping projects by portfolio as you have said and then collecting all portfolio ids that return, and running a second query to get portfolios with
{_id: {$nin: <array of already returned portfolio ids>}}
Both options have pros and cons but currently these are the only two options that I can think of.
Because I cannot edit properties of a non-lean mongoose result, I've used the result.toObject() statement, but that also means I cannot use the methods defined on my Schema.
Example
// Defining the schema and document methods
const User = new Schema({
email: {type: String, required: true, unique: true},
firstname: {type: String, required: true},
registration_date: {type: Date, default: Date.now, required: true},
insert: {type: String},
lastname: {type: String, required: true}
});
User.methods.whatIsYourFirstName = function () {
return `Hello, my firstname is:${this.firstname}`;
};
After a find:
user = user.toObject();
user.registration_date = moment(user.registration_date);
user.whatIsYourFirstName();
// result in "user.whatIsYourFirstName is not a function"
Is this solvable?
Methods and Models are part of Mongoose, not MongoDB.
Whenever you are calling .toObject() you are being returned an object which is ready for storage in MongoDB.
If you do need to do any sort of value transformation, I'd do it just before you deliver the value to the user. Being a time formatting, if you are building an API, I'd do that in the client; if you are working with templates try transforming the value on the same template.
Sorry for the vague title, but what I'm trying to do is the following:
I've got 2 mongoose Models: posts and users (which can be the author of a post)
const Post = new Schema({
title: {type: String, required: true, unique: true},
content: {type: String, required: true},
date_created: {type: Date, required: true, default: Date.now},
authorId: {type: String, required: true}, // ObjectId
author: {type: Schema.Types.Mixed},
page: {type: Boolean, required: true, default: false}
});
post.find()
mongoose sends query to MongoDB
MongoDB returns documents
Middleware that retrieves the author based on the authorId property
Add found user to the posts author field
post.find callback
Is this possible?
yes, mongoose document references and population will do this for you.
const Post = new Schema({
// ...
author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: "User"}
});
the ref: "User" tells Mongoose to use the "User" type as the object type. Be sure you have a "User" model defined with Mongoose or this will fail.
to load the full object graph, use the populate method of a query:
Post
.findOne(/* ... */)
.populate('author')
.exec(function (err, story) {
// ...
});
P.S. I cover this and more in my MongooseJS Fundamentals screencast package.
I have two mongoose Schemas which look like this:
var FlowsSchema = new Schema({
name: {type: String, required: true},
description: {type: String},
active: {type: Boolean, default: false},
product: {type: Schema.ObjectId, ref: 'ClientProduct'},
type: {type: Schema.ObjectId, ref: 'ConversionType'},
});
this schema is then embedded in a parent schema that looks like this:
var ClientCampaignSchema = new Schema({
name: {type: String, required: true},
description: {type: String},
active: {type: Boolean, default: false},
activeFrom: {type: Date},
activeUntil: {type: Date},
client: {type: Schema.ObjectId, ref: 'Client', required: true},
flows: [FlowsSchema]
});
and
var ConversionTypeSchema = new Schema({
name: {type: Schema.Types.Mixed, required: true},
requiresProductAssociation: {type: Boolean, default: false}
});
As you can see my FlowsSchema holds a reference towards the ConversionType. What I want to do is only allow a product to be added to a flow, if the associated conversiontype's 'requiresProductAssociation' is equal to true.
Unfortunately, wether I use validators or middleware this would mean making a call to mongoose.model('ConversionType') which is automatically async and messes things up. What do?
p.s. if there would be a way to store a reference to that requiresProductAssociation boolean rather than the entire object that would be great because I wouldn't need to make the async call to that model anymore, but I don't know if that's possible.
The docs for SchemaType#validate describe how to perform asynchronous validation for cases like this. An asynchronous validator function receives two arguments, the second being a callback function you call to asynchronously report whether the value is valid.
That lets you implement this validation as:
FlowsSchema.path('type').validate(function(value, respond) {
mongoose.model('ConversionType').findById(value, function(err, doc) {
respond(doc && doc.requiresProductAssociation);
});
});