mongoose : how to validate field depend on other field value - mongodb

I want to require field depend on other field value; I have field paypaleEmail , I want it to be required when field role is "particular" otherwise not required.
paypalEmail: {
type: String,
required: function () { return this.role == 'particular', 'Paypal Email is required' },
trim: true,
validate: {
validator(email) {
return validator.isEmail(email)
},
message: '{VALUE} is not a valid email!',
},
lowercase: true,
},
when try to send request I got paypalEmail is required

The "required" function should return a boolean.
Your
function () { return this.role == 'particular', 'Paypal Email is required' }
Unconditionally returns string 'Paypal Email is required' which evaluates to true when casted to bool.
function () { return this.role == 'particular' }
Should do what you expect.

Related

How to specify that at least one field is required out of three in total?

In my MongoDB model, there are 3 fields in total. Any document added to this collection must contain at least 1 of those 3 fields.
How can this be specified in the validation staged?
You can enum validation constraint which collection creation as below:
db.createCollection("jobs", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "status" ],
properties: {
status: {
enum: [ "Done", "Failed", "Initial" ],
description: "can only be one of the enum values and is required"
},
}
}
}
})
From the docs
Mongoose has several inbuilt validators. Strings have enum as one of the validators. So enum creates a validator and checks if the value is given in an array. E.g:
var userSchema = new mongooseSchema({
status: {
type: String,
enum : ['Done','Failed', 'Initial'],
default: 'Initial'
},
})
You can use custom validator to check if we have one of 3 keys in the object
const testSchema = mongoose.Schema({
field1: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field2: {
type: String,
validate: {
validator: function(v) {
if (this.field1 == undefined && this.field3 == undefined) {
return true;
}
return false;
},
},
},
field3: {
type: String,
validate: {
validator: function(v) {
if (this.field2 == undefined && this.field1 == undefined) {
return true;
}
return false;
},
},
},
});

Why isn't my Getter function working with Mongoose?

I have a getter on the price property of my schema.
For some reason, my getter function is not working when I try to query a document from my MongoDB database. The price value comes back exactly as I have it saved in my database, as opposed to a rounded number via Math.floor(v). Fyi, my setter works fine in the same scenario. Any help would be much appreciated!
const schema = mongoose.Schema({
name: { type: String, required: true, lowercase: true },
isPublished: Boolean,
author: {
type: String,
required: function (v) {
return this.isPublished;
},
uppercase:true,
},
price: {
type: Number,
required: true,
get: function (v) {
return Math.floor(v);
},
},
});
const Documents = mongoose.model("Documents", schema);
async function myQuery(id) {
const result = await Documents.findById(id);
if (!result) return debug("Not found...");
debug(result);
}
myQuery("60348d30e7b9bf3878170955");
const schema = mongoose.Schema({
name: { type: String, required: true, lowercase: true },
isPublished: Boolean,
author: {
type: String,
required: function (v) {
return this.isPublished;
},
uppercase: true,
},
price: {
type: Number,
required: true,
get: function (v) {
return Math.floor(v);
},
},
} {
toObject: { getters: true, setters: true },
toJSON: { getters: true, setters: true },
runSettersOnQuery: true
});
Add the following configuration to your schema and give it a try.

How to solve MongoError: E11000 duplicate key error collection

I am Working in a MERN application. In one of my model of express.js I have student schema like below which have unique fields
Fullname: {
type: String,
required: true,
trim: true,
},
AdmissionNumber: {
type: String,
required: true,
trim: true,
maxlength: 10,
unique: true,
},
RollNumber: {
type: Number,
required: true,
trim: true,
maxlength: 4,
},
Age: {
type: Number,
required: true,
maxlength: 2,
},
Email: {
type: String,
trim: true,
required: true,
unique: true,
},
Faculty: {
type: ObjectId,
ref: "Faculty",
required: true,
},
pass: {
type: Number,
default: 0,
}
I am saving the student with the help of form like this
exports.addStudent = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields) => {
if (err) {
res.status(400).json({
error: "problem with feilds",
});
}
// destructuring feilds
const {
Fullname,
AdmissionNumber,
RollNumber,
Age,
Email,
Faculty,
} = fields;
if (
!Fullname ||
!AdmissionNumber ||
!RollNumber ||
!Age ||
!Email ||
!Faculty
) {
return res.status(400).json({
error: "Please fill all fields",
});
}
// TODO: restriction on fields
let student = new Student(fields);
student.save((err, student) => {
if (err) {
res.status(400).json({
error: "Saving Student in DB failed",
});
console.log(err);
}
res.json(student);
// console.log(student.gender);
});
});
};
When I try to add student it will be added only first time after that it showing an error
I have checked my DB collection there is only one field in the database.
I had this problem before and the solution that worked for me is to delete the collection from the database then try again

mongoose - how to get a schema's final document without an insertion

Say I have a schema like this.
{
__content: {
default: "",
index: true,
type: Mixed,
validate: {
validator(v)
{
return !!(
typeof v === "string" ||
(
typeof v === "object" &&
!Array.isArray(v)
)
)
}
}
},
__hidden: {
default: false,
index: true,
type: Boolean
},
__title: {
required: true,
index: true,
type: String,
},
__type: {
default: "text",
enum: ["text", "table"],
index: true,
type: String
},
}
Is it possible to return what the schema would be like if I made a blank insert e.g. Model.create({}) without an actual insertion? Right now, my idea is to insert it into a throwaway collection and just get the return

Creating custom attributes in Sailsjs

I am trying to create a custom attribute in my sails app and I am not getting any result back in my get call.
My code looks something like this:
module.exports = {
attributes: {
id: {
type: 'string',
primaryKey: true,
defaultsTo: function () {
return uuid.v4();
},
unique: true,
index: true,
uuidv4: true
},
name: {
type: 'string',
required: true
}
fullName: function(){
return this.name ;
}
};
I get back all the fields expect full Name
In my opinion the sailsjs model attributes only create corresponding column and get the column in database based on the type. In your case, the fullName has no type. so it does not know what to get from database.
However, if what you want is the returned json object has some extra fields, you can overwrite the toJSON function to add it.
module.exports={
attributes:
id: {
type: 'string',
primaryKey: true,
defaultsTo: function () {
return uuid.v4();
},
unique: true,
index: true,
uuidv4: true
},
name: {
type: 'string',
required: true
},
toJSON:function(){
var obj=this.toObject();
obj.fullName=obj.name;
return obj;
}
}
}
This issue is a little old, but I've a better answer:
module.exports = {
attributes: {
firstname : 'string',
lastname : 'string,
fullName: function () {
return this.firstname + ' ' + this.lastname
}
toJSON:function(){
var obj = this.toObject();
obj.fullName = this.fullName()
return obj;
}
}
}