Mongoose enum Validation on String Arrays? - arrays

Is it possible to use enum validation on type: [String]?
Example:
var permitted = ['1','2','3'];
var exampleSchema = new Schema({
factors: {
type: [String],
enum: permitted,
required: "Please specify at least one factor."
}
});
I would have expected that factors would only be able to contain the values in permitted.

This is working fine for me (mongoose#4.1.8)
var schema = new mongoose.Schema({
factors: [{type: String, enum: ['1', '2', '3'], required: ...}]
...
})
Note I'm using an Array of Objects

As of mongoose version 5.0.6 and higher, the OP issue now works!
factors: {
type: [String],
enum: permitted,
required: "Please specify at least one factor."
}
Reference
https://github.com/Automattic/mongoose/issues/6204#issuecomment-374690551

TRY THIS
let inventory_type_enum = ["goods", "services"];
inventory_type: {
type: String,
enum: inventory_type_enum,
validate: {
// validator: (inventory_type) => !inventory_type.enum.includes(inventory_type),
validator: (inventory_type) => inventory_type_enum.includes(inventory_type),
message: languages('general_merchandise_model','inventory_type')
},
required : [true, languages('general_merchandise_model','inventory_type_required')],
},

Mongoose before version 4.0 didn't support validation on Schema static methods like .update, .findByIdAndUpdate, .findOneAndUpdate.
But it supports on instance method document.save().
So, either use document.save() for inbuilt initiating validation
or this { runValidators: true } with methods like .update, .findByIdAndUpdate, .findOneAndUpdate.
reference:
Mongoose .update() does not trigger validation checking

if you have enuns or you have object enuns
brand: {
type: String,
required: true,
enum: Object.values(TypeBrandEnum)
},

you can use something like this
{
factors: [
{
type: [String],
enum: ['1', '2', '3'],
},
],
}

Related

How to find a particular sub-document in MongoDB?

This thread states that it is not a very good idea to create _id in a sub-document of MongoDB.
Mongo _id for subdocument array
I have locations and their reviews in a collection:
So, what would be the way to find a unique sub-document?
What can be set as a primary key for review sub-document?
var mongoose = require('mongoose')
var openingClosingTimeSchema = new mongoose.Schema(
{
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: String, required: true}
}
)
var reviewSchema = new mongoose.Schema(
{
author: String,
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: String,
createdOn: {type: Date, default: Date.now}
}
)
var locationSchema = new mongoose.Schema(
{
// 'required' keyword is for validation.
name: {type: String, required: true},
address: String,
// 'default' keyword can be with or without quotes.
// When defining multiple properties for a field, {} are required.
rating: {type: Number, default: 0, min: 0, max: 5},
facilities: [String],
// Nest 'openingClosingTimeSchema' under 'locationSchema'.
openingTimes: [openingClosingTimeSchema],
// Nest 'reviewSchema' under 'locationSchema'.
reviews: [reviewSchema]
}
)
it is not a very good idea to create _id in a sub-document of MongoDB
This is not a universally applicable guideline.
If you need to identify subdocuments in an array, an _id field would be helpful (or any other field that would serve the same function).
If you don't need to identify subdocuments, you don't need an identification field.
Since you are in the first category it's perfectly ok to have an _id field in your use case.

How to add value to array element withing collection using mongoose?

I have written the following mongoose function to create new document in mongodb
createdata: (body) => {
let sEntry = new SData(Object.assign({}, {
dataId: body.DataId
//,
//notes.message: body.message
}));
return sEntry.save();
}
Here sData schema includes notes array schema within it.
I am not able to add value to message within notes [] using notes.message: body.message
My schema definition is as follows:
var nSchema = new Schema({
_id: {type:ObjectId, auto: true },
message: String
});
var sSchema = new Schema({
_id: {type:ObjectId, auto: true },
dataId: { type:String, unique: true },
notes: [nSchema]
}
I also want to mention that for every dataId there can be multiple notes [] entries. However, SData can have only unique row entry for every dataId.
I want notes to be an array within SData collection. How it can be achieved without creating separate notes collection? How should i modify createdata to accommodate all the given requirements.
Use references for other collection mapping and use populate when fetching
Schema Design
var sSchema = new Schema({
_id: {type:ObjectId, auto: true },
dataId: { type:String, unique: true },
notes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'nSchema',
}]
}
Adding Data
createdata: (body) => {
let sEntry = new SData({
dataId: body.DataId,
notes: [nSchemaIds]
});
return sEntry.save();
}

Mongo schema, array of string with unique values

I'm creating the schema for a mongo document and I can do everything except prevent duplicates in a non-object array.
I'm aware of the addToSet, but I'm referring to Mongo Schema.
I don't want to check on Update using $addToSet, rather I want this to be part of my schema validation.
Example below.
let sampleSchema = {
name: { type: 'String', unique: true },
tags: [{ type: 'String', unique: true }]
}
The above snippet prevents name from having duplicate values. It allows tags to be stored as a string array.
But.. I cannot limit the array to be unique strings.
{ name: 'fail scenario', tags: ['bad', 'bad', 'array']}
I'm able to insert this record which should be a fail scenario.
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const _ = require('underscore');
let sampleSchema = new mongoose.Schema({
name: {
type: 'String',
unique: true
},
tags: [{
type: 'String'
}]
})
sampleSchema.pre('save', function (next) {
this.tags = _.uniq(this.tags);
next();
});
const Sample = mongoose.model('sample', sampleSchema, 'samples');
router.post('/sample', function (req, res, next) {
const sample = new Sample(req.body);
sample.save()
.then((sample) => {
return res.send(sample);
})
.catch(err => {
return res.status(500).send(err.message);
})
});
I've come to the conclusion that this is impossible to do via Mongoose Schema.
JSON schema is done like so.
let schema = {
name: { type: 'string' }
tags: {
type: 'array',
items: { type: 'string', uniqueItems: true }
}
}
I'll validate with JSON schema before creating Mongo Document.
This method builds on Med's answer, handles references, and done completely in scheme validation.
let sampleSchema = new mongoose.Schema({
strings: [{type: 'String'}],
references: [{type: mongoose.Schema.Types.ObjectId, ref: 'Reference'],
});
sampleSchema.pre('save', function (next) {
let sample = this;
sample.strings = _.uniq(sample.strings, function(i) {return (i._id) ? i._id.toString() : i;});
sample.references = _.uniq(sample.references, function(i) {return (i._id) ? i._id.toString() : i;});
return next();
});
I'm a little late, but maybe this will help someone in the future.
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
},
reference: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'SomeOtherSchema',
// Add a custom validator.
validate: {
// The actual validator function goes here.
// "arr" will be the value that's being validated (so an array of
// mongoose new ObjectId statements, in this case).
validator: arr => {
// Convert all of the items in the array "arr", to their string
// representations.
// Then, use those strings to create a Set (which only stores unique
// values).
const s = new Set(arr.map(String));
// Compare the Set and Array's sizes, to see if there were any
// duplicates. If they're not equal, there was a duplicate, and
// validation will fail.
return s.size === arr.length;
},
// Provide a more meaningful error message.
message: p => `The values provided for '${ p.path }', ` +
`[${ p.value }], contains duplicates.`,
}
},
});
The above commented code should be pretty self explanatory.
With the newer version(s) of MongoDB, you can use $addToSet to append to an array if and only if the new value is unique compared to the items of the array.
Here's the reference: https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/
Here's an example:
const SampleSchema = new mongoose.Schema({
tags: [String]
});
const Sample = mongoose.model('Sample', SampleSchema);
// append to array only if value is unique
Sample.findByIdAndUpdate({_id: 1, {$addToSet: {tags: "New Tag"}}});
This will effectively update the tags if the "New Tag" is not already present in the tags array. Otherwise, no operation is done.

Mongoose: Validation not being executed when saving

I've defined this Mongoose schema:
// validator function
var arrayWithAtLeastFiveElements = function (a) {
return (a !== undefined && a.length >= 5);
};
var orderSchema = new Schema({
user: {
type: Schema.ObjectId,
ref: User,
required: true
},
products: [{
type: Schema.ObjectId,
ref: Product,
required: true,
validate: [arrayWithAtLeastFiveElements, 'Order needs to have at least five products']
}]
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
When I try to save it, the validation is not executed if products is undefined, null or an empty array, and it saves the new order with an empty array of products in each case. The validations are only run when products is an array with at least one element. Any clue what's going on? It there a way to make the validation run in all cases? Also, what does require do in this case? I don't see any change in validations if I define products array as required or not...
Define it with:
products: {
type: [Schema.ObjectId],
required: true,
}

How to query mongoose by property that is and array item

I have a mongoose model that looks like this:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var PictureSchema = new Schema({
listId: { type: Array, required: true },
thumb: { type: String, required: true },
large: { type: String, required: true }
});
var Picture = module.exports = mongoose.model('Picture', PictureSchema);
I am trying to update instances of this model in my router by looking up a Picture via the "listId" property. Like this:
app.put('/pictures/append', function(req, res) {
var targetListId = req.body.targetListId
, currentListId = req.body.currentListId;
Picture
.find({ listId: currentListId }, function (err, picture) {
console.log('found pic', picture);
picture.listId.push(targetListId);
picture.save(function(err, pic) {
console.log('pic SAVED', pic);
});
});
});
"currentListId" is a string, and listId is an array of currentListId's. Maybe this isn't the correct way to query a a property that is an array?
I am getting an error:
TypeError: Cannot call method 'push' of undefined
On the line:
picture.listId.push(targetListId);
But when I look up the picture models in mongo, they DO have listId arrays and some DO contain the item "currentListId" that I am using for my query.
I tried using $elemMatch and $in but I don't know if I was using them correctly.
Any idea if I am just writing my query wrong?
Specifying an Array typed field in your schema is equivalent to Mixed which tells Mongoose that field could contain anything. Instead, change your schema to something like this:
var PictureSchema = new Schema({
listId: [String],
thumb: { type: String, required: true },
large: { type: String, required: true }
});

Resources