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
Related
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)
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.
This is my user Schema where I have addresses as array
name: {
type: String,
unique: true,
require: true
},
email: {
type: String,
trim: true,
lowercase: true,
unique: true,
required: "Email address is required"
},
password: {
type: String,
required: true,
min: [6, "Password must be atlest 6 characters length"]
},
mobile: {
type: String,
required: true,
unique: true
},
image: {
type: String,
default: "gravatar.png"
},
addresses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Address"
}
],
cart: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Cart"
}
],
orderHistory: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "OrderHistory"
}
]
});
This is post request to /user/address route where I want to create a new Address, link the user collection and address collection and populate the user collection. But it is giving me an error
"TypeError: Address.create(...).then(...).populate is not a function". I also used exec() method. I think I am not using populate and exec method correctly.
router.post("/address", function(req, res) {
console.log("form data: ", req.body);
Address.create(req.body)
.then(function(newAddr) {
// console.log(newAddr);
return User.findByIdAndUpdate(
{ _id: req.session.user._id },
{ $push: { addresses: newAddr._id } },
{ new: true }
);
})
.populate("addresses")
// .exec((err, updatedUser) => {
// if (err) {
// res.send(err);
// } else {
// console.log(updatedUser);
// res.redirect("/user");
// }
// });
.then(function(updatedUser) {
res.redirect("/user");
})
.catch(err => {
res.send(err);
});
});
I want to create new user and save into user table in my data base
i act as follows:
create: function(req,res,next){
bcrypt.hash(req.param('password'),10,function (err, hashed) {
if (err) {
console.log("4");
return res.serverError({'err': 'hash Error!'});
} else{
User.create({
username: req.param('username'),
password: hashed,
type: req.param('type')
},function (err, created_user) {
if (err) {
err = validator(User, err);
return res.json({'status': false, 'errors': err.Errors});
}
return res.json({'status': true, 'result': created_user});
}
);
}
}
}
My User Model is:
module.exports = {
attributes: {
username: {
type: 'string',
required: true,
unique: true
},
password: {
type: 'string',
required: true
},
type: {
type: 'number',
columnType: 'integer'
},
last_x_map: {
type: 'number',
columnType: 'float'
},
last_y_map: {
type: 'number',
columnType: 'float'
},
places :{
collection: 'place',
via: 'user_owner'
},
},
validationMessages: {
username:{
required: '...',
alphanumericdashed: '...',
unique: '...'
},
password: {
required: '...'
}
},
But it always return false and do not any thing.
Where is the problem?
Or what do you recommend for this?
thanks a lot.
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);
}
};