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);
});
});
Related
const walletTransactionSchema = new mongoose.Schema({
a: {type: Boolean, required: true},
},
{timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}});
const walletSchema = new Schema({
b: {type: Boolean, required: true},
transactions: [{type: walletTransactionSchema}],
});
walletSchema.index({'transactions': 1}, {sparse: true});
module.exports.Wallet = mongoose.model('Wallet', walletSchema, 'wallets');
module.exports.WalletTransaction = mongoose.model('WalletTransaction', walletTransactionSchema);
I'm trying to create a model for a subdocument (WalletTransaction) without creating a collection for it. Unfortunately mongoose is automatically creating that collection. How can I prevent that behavior and just define a sub-model without creating a collection. I prefer to organize my schemas by refactoring them instead of just embedding them.
I used to do this without trouble with above definitions. I guess after updating to mongoose 6.0.8 (from 5.13) this is happend.
if you wanna create another model inside a model
You should go with the following approach
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: {
type: String,
required: true},
about:{type:String},
password: {type: String, required: true},
friends: [new mongoose.Schema({
user: {type: String}
}, {strict: false})],
profileImage: {type: String, default: "default.jpg"},
userName: {type: String, required: true},
matches: {type: Number, default: 0},
wins: {type: Number, default: 0},
losses: {type: Number, default: 0},
backgroundImage: {type: String, default: "default.jpg"},
resetPasswordToken: {type: String, required: false},
resetPasswordExpires: {type: Date, required: false},
isDeleted: {type: Boolean, default: false},
deletedAt: {type: Date, default: null},
}, {timestamps: true}, {strict: false});
module.exports = mongoose.model('User', userSchema);
Like this I create another model in my User model with name Friends in which each entry has one specific id
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".
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.