beforeCreate not executing when trying to create entry - Sails JS - node.js

I've got a user model, and I'm just trying to test out beforeCreate by returning err, but when I do POST /user it creates the model fine, without executing the beforeCreate method. What am I doing wrong here? Here's models/User.js:
module.exports = {
connection: "mysql",
attributes: {
firstname: {
type: "string",
required: true
},
lastname: {
type: "string",
required: true
},
fullname: function() {
return this.firstname + ' ' + this.lastname;
},
username: {
type: "string",
required: true
},
password: {
type: "string",
required: true
},
email: {
type: "email",
required: true
},
status: {
type: "integer",
/*
* 0 - unconfirmed, 1 - confirmed, 2- suspended
*/
enum: [0, 1, 2]
},
// Override toJSON instance method to remove password value
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
},
// Associations
roles: {
collection: "role",
via: "users"
},
permissions: {
collection: "permission",
via: "users"
},
// Lifecycle Callbacks
beforeCreate: function(values, next) {
return next(err);
}
}
};

beforeCreate is not an attribute but a method on the model, so it should be like this:
attributes: {
....
},
beforeCreate: {
....
}

Your beforeCreate got inside attributes. It have to be on the outside. like -
module.exports = {
connection: "mysql",
attributes: {
firstname: {
type: "string",
required: true
},
lastname: {
type: "string",
required: true
},
fullname: function() {
return this.firstname + ' ' + this.lastname;
},
username: {
type: "string",
required: true
},
password: {
type: "string",
required: true
},
email: {
type: "email",
required: true
},
status: {
type: "integer",
/*
* 0 - unconfirmed, 1 - confirmed, 2- suspended
*/
enum: [0, 1, 2]
},
// Override toJSON instance method to remove password value
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
},
// Associations
roles: {
collection: "role",
via: "users"
},
permissions: {
collection: "permission",
via: "users"
}
},
beforeCreate: function(values, next){
return next(err);
}
};

Related

Can't create second model document with mongoose

the first document i am creating with this model is good but when creating second document using this model i am getting this error i tried change the _id to id and thats didn't work
const classSchema = new Schema({
prettyId: {
type: Number,
},
name: {
type: String,
required: true,
},
students: [
{
name: {
type: String,
},
_id: {
type: Schema.Types.ObjectId,
ref: "Student",
},
prettyId: {
type: Number,
},
},
],
teachers: [
{
_id: {
type: Schema.Types.ObjectId,
ref: "Teacher",
},
name: {
type: String,
},
prettyId: {
type: Number,
},
},
],
});
classSchema.plugin(AutoIncrement, {
id: "classId",
inc_field: "prettyId",
start_seq: 10000,
inc_amount: 1,
disable_hooks: false,
});
the error i am getting is
return callback(new error_1.MongoServerError(res.writeErrors[0]));
^
MongoServerError: E11000 duplicate key error collection: school.classes index: teachers.id_1 dup key: { teachers.id: null }
{
index: 0,
code: 11000,
keyPattern: { 'teachers.id': 1 },
keyValue: { 'teachers.id': null },
[Symbol(errorLabels)]: Set(0) {}
}
the controller which i create from it the class
exports.newClass = async (req, res, next) => {
const { name } = req.body;
const myClass = new Class({
name: name,
teachers: [],
students: [],
});
await myClass.save();
res.json({ message: "class createad", myClass });
};
It often happens when you have previously used the collection with different parameters. A quick fix would be to delete the collection and try to see if it works.

Want to use mongoose updateOne but it is not updating

I want to update the type: reported to type: pending under the reportStatus, but when I try it on postman I keep on getting
n:1 ,n:modified:1 and ok:1
report: [
{
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "CrimeCategory",
required: true,
},
location: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
reportText: {
type: String,
required: true,
},
reportStatus: {
type: mongoose.Schema.Types.Mixed,
default: function () {
return [
{ type: "reported", date: new Date(), isCompleted: true },
{ type: "pending", isCompleted: false },
{ type: "investigating", isCompleted: false },
{ type: "solved", isCompleted: false },
];
},
},
},
],
This is the controller where I am trying to update the types that is in the model, what am I doing wrong?
const crimeReport = require("../../model/crimereport");
exports.updateReport = (req, res) => {
crimeReport
.updateOne(
{ _id: req.body.reportId, "report.reportStatus": req.body.type },
{
$set: {
"report.reportStatus.$": [
{
type: req.body.type,
date: new Date(),
isCompleted: true,
},
],
},
}
)
.exec((error, report) => {
if (error) return res.status(400).json({ error });
if (report) {
res.status(200).json({ report });
}
});
};
The postman post request:
{
"reportId": "607b2b25876fa73ec4437440",
"type":"pending"
}
This is the post result from postman:
{
"report": {
"n": 0,
"nModified": 0,
"ok": 1
}
}
It seems like, you are sending reportId in the body of post request as a string while the Mongodb document's id is of type ObjectId. You need to typecast the reportId into ObjectId, before querying to Mongodb. Since you are using Mongoose, this is the way it should be done:
mongoose.Types.ObjectId(req.body.reportId)

Hide associate model's data in sails

I have two model
Account.js and Content.js
In content.js i have associated Account model like this
module.exports = {
attributes: {
title: { type: "string" },
description: { type: "string" },
userId: { model: "account", required: true },
categoryId: { model: "contentcategory" },
},
};
In account.js model file
i have
module.exports = {
attributes: {
fName: { type: "string" },
lName: { type: "string" },
pass: { type: "string", required: true },
email: { type: "string", required: true, isEmail: true, unique: true },
phone: { type: "number" },
walletBalance: { type: "number", defaultsTo: 0 },
},
};
When fetching the a content I get list of content that also includes account details.
{
title:"category Name",
description : "CAtegort Desc",
userId : {
id: 12552,
fName:John,
lName:Doe,
pass : "23623562356",
email:"john Doe",
phone: "124151516",
walletBalance: 234
}
}
I want only the fname and lname of the user and hide pass, walletbalance etc, how can i do it sails waterline
You have to use customToJSON as mentioned in the docs.
with the following sentence to hide unwanted fields in account.js:
customToJSON: function () {
return _.omit(this, ['pass', 'email', 'phone', 'walletBalance'])
},
Add it after model's attribute object.

Add data in an array of object with mongoDB

I need your help, I try to add(if it not exists) or update if exists datas in an array of Object in MongoDB.
Here is my Model
import { Schema, model } from "mongoose";
const userSchema = new Schema({
firstName: {
type: String,
required: true,
unique: false,
trim: true
},
pseudo: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
email: {
type: String,
required: false,
trim: true
},
password: {
type: String,
required: true
},
// password2: {
// type: String,
// required: true
// },
tags: {
type: Array,
required: false
},
address: {
type: String,
required: true,
unique: false,
trim: true
},
coord: {
type: Object,
required: false,
unique: false,
trim: true
},
poll: [
{
tag: String,
dates: Array
}
]
},
{
timestamps: true,
});
const User = model('User', userSchema);
export default User;
My route
router.route('/calendar/:email').post((req, res) => {
User.findOne({ email: req.body.email }).then( (user) =>{
console.log("user 1", user)
User.bulkWrite([
{
insertOne: {
"poll": {
"tag": req.body.selectedTag,
"dates": req.body.datesArray
}
}
},
{
updateOne: {
"filter": {
"tag" : req.body.selectedTag
},
"update": {
$set: {
"dates": req.body.datesArray
}
},
}
}
])
})
});
and the datas sended :
email: 'john#gmail.com',
selectedTag: 'work',
dateArray: [ '2020-07-16T22:00:00.000Z' ]
I try many things like by findOneaAndUpdate, but I don't know how to add in the array "poll", objects with tag and the dates associated.
If somebody could help me it would be very nice !
I shoul use add $addToSet or $push, depending if the element is unique or not.
Something like this:
"update": {
"$addToSet": {
"poll": { /*...*/ }
}
}
For reference:
http://docs.mongodb.org/manual/reference/operator/update/addToSet/
http://docs.mongodb.org/manual/reference/operator/update/push/

Sails.js E_VALIDATION error

I'm starting in sails.js by following a tuto and the sails.js doc .
I'm creating a user account system, when I try to create a new user thru de user form a get this error :
{
"error": "E_VALIDATION",
"status": 400,
"summary": "1 attribute is invalid",
"model": "User",
"invalidAttributes": {
"hashedPassword": [
{
"rule": "string",
"message": "`undefined` should be a string (instead of \"null\", which is a object)"
},
{
"rule": "required",
"message": "\"required\" validation rule failed for input: null"
}
]
}
}
You can see my model below :
module.exports = {
attributes: {
name: { type: 'string', required: true },
username: { type: 'string', required: true },
email: { type: 'string', lowercase: true, email: true, required: true, unique: true },
role: { type: 'string', default: 'user' },
hashedPassword: { type: 'string', required: true },
provider: 'string',
salt: 'string',
facebook: {},
twitter: {},
google: {},
github: {}
}
};
And my controller:
module.exports = {
'new': function(req, res){
res.view();
},
'create': function(req, res, next){
User.create(req.params.all(), function userCreated(err, user) {
if (err) return next(err);
res.json(user);
});
}
};
Any help please ? thanks

Resources