Possible to have `validate` fail on not specified elements? - javascript

The below returns success, even though obj contains an element that is not in the schema.
Question
Is it possible to have validate fail, when it sees elements that are not specified in the schema?
Jest have this expect(obj1).toEqual(obj2).
If Validate can't do it, what options do I then have to detect unwanted elements?
const Schema = require("validate");
const obj = {good: "1", bad: "2"};
const user = new Schema({
good: {
type: String,
required: true,
}
});
const r = user.validate(obj);
console.log(r);

Yes, there is a strict option on the Schema, from the documentation:
Schema
A Schema defines the structure that objects should be validated against.
Parameters
obj schema definition
opts options
opts.typecast
opts.strip
opts.strict
Validation fails when object contains properties not defined in the schema
(optional, default false)
So you'll need something like:
const options = { strict: true };
const user = new Schema({
good: {
type: String,
required: true,
}
}, options);

Related

how to add array of particular schema type in mongoose?

i want to add that question schema as the type inside that questions array in topicSchema, but cant do that as it gives error. How can i add array of particular schema type. Is there a way?
const question_schema = require('./Question')
const topicSchema = new Schema(
{
name: {
type: String,
required: true,
enum: [...Object.values(topics_enum)]
},
icon: {
type: String,
required: true
},
questions: [question_schema]
},
{
versionKey: false,
}
);
module.exports = mongoose.model("topics", topicSchema);
To my understanding, use type and ref,
you need to use this formatting in order to reference the schema itself:
questions: [{
type: Schema.Types.ObjectId,
ref: 'question_schema'
}
],
The type (Schema.Types.ObjectId) will add the object id for each question in the array (which you can then iterate over later to find each question by those IDs), and the ref ('question_schema') allows mongoose to figure out which of your schemas it should be referencing. As long as the ref is the same as your variable name, it should connect using ref.
You need to state the type of the object as an array, try:
questions:{
type: [question_schema],
}

Mongoose schema either single object or array of objects based on condition

I have the following schema:
const contentSchema = new Schema({
name: {
type: String,
required: true
},
type: {
type: String,
required: true
},
value: {
type: String,
required: true
}
});
const contentArraySchema = new Schema({
contentArray: [contentSchema]
});
const pageSchema = new Schema({
contents: [contentSchema]
});
I would like to have a mix of objects and arrays added to the pageSchema. If I have an array I would like to populate it with the contentSchema objects and then add that to the pageSchema contents field array. If I don't have an array I would just like to add the contentSchema object to the pageSchema contents field array.
I was just going to use the mixed schema type but I'm not sure what the best way to go about doing this would be and what effect that would have on basic database searching.
I also thought about doing something like I saw on this post Here:
pageSchema.pre('validate', function (next) {
if (type === 'array') {
//use content array schema
} else {
//use regular content schema
}
next()
});
But I'm not really sure what the best practice is for something like this. Hopefully someone has some experience with this and can help. Thanks.

The same default value gets used every time by `new mongoose.Schema`

I have problem using uuid with new mongoose.Schema. I use it to generate unique key for a device and save it to the MongoDb using Node.js. the problem is that it uses the same UUID every time.
This is the model:
const mongoose = require('mongoose');
const uuid = require('uuid/v4');
const DeviceSchema = new mongoose.Schema({
deviceNumberHash: {
type: String,
required: true
},
receivingKey: {
type: String,
default: uuid()
}...
});
And this is what is saved in MongoDb:
Any idea what's wrong?
You're calling uuid and passing its return value in as the default to use.
Instead, pass in the function (by not putting () after it):
const DeviceSchema = new mongoose.Schema({
deviceNumberHash: {
type: String,
required: true
},
receivingKey: {
type: String,
default: uuid // <========== No ()
}...
});
The default can be a function per the docs (an example there uses default: Date.now to provide a default for a date field, for instance).

Is there a way to get the model name from a mongoose model instance?

I´m using mongoose and I need to find a model name from a model instance.
In one part of the code I have:
const schema = new mongoose.Schema({
name: {
type: String,
required: true
},
phone: {
type: String,
required: true
}
}
const schema = new mongoose.Schema('MyData', schema);
let instance = new this({
name: 'Pete',
phone: '123'
});
Ths instance variable is passed around in my code. Later I need to find out instance name, but I´m no sure if there is a way to do it, something like:
let instanceName = getInstanceName(instance); <== Expects 'MyData' to be returned
Is that possible using mongoose ?
I realized I had a model not an instance of a model so I needed to use something else.
If you have a model, you can get the name as below:
const model = mongoose.model("TestModel", schema);
const collectionName = model.collection.collectionName;
If you have a specific item/instance of the model:
const instance = new model({...});
const collectionName = instance.constructor.modelName
as Hannah posted.
The name of the model can be accessed using this instance.constructor.modelName.
In my case I was looking for how to get a discriminator model name from a mongoose model, and the suggested solutions didn't work:
const PerformanceResult = DropDown.discriminator('PerformanceResult', new db.Schema({
name: { type: String, required: true }
}))
export default PerformanceResult
console.log(PerformanceResult.constructor.modelName) // undefined
console.log(PerformanceResult.collection.collectionName) // DropDown (parent name)
you can use this:
console.log(PerformanceResult.modelName) // PerformanceResult
mongoose version: "^5.11.8"

Mongo reference field not instantiating when using underscore js map function,

GridComponent model has reference id (field is componentid) to Component model
_.map(components,function (component){
var foo = (new Component())._id;
component.componentid = foo;
var gc = new GridComponent(component);
assert(typeof gc.componentid !== 'undefined');
})
fails yet
_.map(components,function (component){
var foo = (new Component())._id;
var testComponent = JSON.parse(JSON.stringify(component));
testComponent['componentid'] = component._id;
var gc = new GridComponent(testComponent);
assert(typeof gc.componentid !== 'undefined');
})
passes, Can anyone explain why
Model used with mongoose and mongodb (recent versions)
var GridComponentSchema = new Schema({
name: String,
quantity: Number,
componentid: {
type: Schema.Types.ObjectId,
ref: 'Component'
},
isNumeric: Boolean,
maxlen: Number,
processid: {
type: Schema.Types.ObjectId,
ref: 'lgProcess'
}
})
Per mongoose doc,
Documents have a toObject method which converts the mongoose document into a plain javascript object. This method accepts a few options. Instead of applying these options on a per-document basis we may declare the options here and have it applied to all of this schemas documents by default.
Or another method toJSON

Categories