I'm trying to customise my Meteor.users schema:
Schema.users = new SimpleSchema({
username: {
type: String,
},
test:{
type: String,
},
services: {
type: Object,
optional: true,
blackbox: true
}
});
And when I call:
Accounts.createUser({username:"lionel",test:"123",password:"123"});
Console returned:
Exception while invoking method 'createUser' Error: Test is required
......
Sanitized and reported to the client as: Test is required [400]
What am i missing here?
Accounts.createUser() expects extra info to come across in a profile key.
Use:
Accounts.createUser({username:"lionel",password:"123",profile: {test:"123"}});
And set up an Accounts.onCreateUser() function on the server:
Accounts.onCreateUser(function(options, user) {
if (options.profile) user.test = options.profile.test;
return user;
});
docs
Related
So I'm trying to access this account by using the findOne function in mongoose, and I'm trying to console.log the error, but the error is just the correct model found.. once I find the correct model I want to access one of the nested objects in the schema so I can edit the value.
I'm not sure why this is happening, below I put the code as well as the error that was logged into the console, I can provide more if needed.
let accountSchema = mongoose.Schema({
username:{
type: String,
required: true,
index: true,
unique: true,
},
password:{
type: String,
required: true,
},
money:{
type: Number,
},
inventory: { type: [{
weed: { type: Number },
coke: { type: Number },
}]},
});
mp.events.addCommand('coke', (player) => {
console.log(player.name);
Account.findOne({username: 'a'}, function(acc, err) {
if(err) return console.log(err);
console.log(acc.username);
acc.inventory[1] = acc.inventory[1] + 1;
acc.save(function(err){
if(err) return player.outputChatBox('Not logged in');
player.outputChatBox('Added 1 coke');
});
});
});
(Console) {"_id":"5b6acbbbc285477e39514cb9","username":"a","password":"$2a$10$XABqooqFRINYVdJ79.i2E.5xdpitRrfZxUBmIPAZjjaXKvvLDc2y2","money":5000,"inventory":[{"_id":"5b6acbbbc285477e39514cbb","weed":0},{"_id":"5b6acbbbc285477e39514cba","coke":0}],"__v":0}
The callback function for the .findOne method has the following signature:
function (err, obj) {
}
You are using the arguments in the wrong order - the error object is the first argument and the object found is the second one.
The .findOne method callback must have the following parameters function (err, res). So you are setting them in a reversed order.
Check http://mongoosejs.com/docs/api.html#model_Model.findOne
I am currently working on a project and I am stuck with inserting an item into an array/object in the database. What I am trying to do is to add the id of a 'upvoted' post to an array/list in the 'User' Collection, however, I cannot seem to get it to work.
The code for my schemas is as follows:
// this is a child scheme/sub-document
var uvpSchema = new Schema();
uvpSchema.add({
post: String
});
var dvpSchema = new Schema();
dvpSchema.add({
post: String
});
//main schema
var userSchema = new Schema({
firstname: { type: String, required: true },
lastname: { type: String, required: true },
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
upVotedPosts: [uvpSchema],
downVotedPosts: [dvpSchema],
created_at: Date,
});
And here is the code in my 'routes.js' to insert the id of the post into the array:
var newPush = {
post: postID // postID is a variable that I have already defined
};
User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
if (err) console.log(err);
user.upVotedPosts.push(newPush);
User.save;
res.redirect(req.get('referer'));
console.log(user.upVotedPosts);
});
The error I receive in my terminal is:
{ _id: 595f68b5fadd49105813f8a4 },{ _id: 595f693d3c2c21189004b0a7 },{ _id: 595f70a2df80e0252894551b }
events.js:163
throw er; // Unhandled 'error' event
^
Thanks in advance ;-)
Route.js
User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
if (err) console.log(err);
user.upVotedPosts.push(newPush);
User.save;
res.redirect(req.get('referer'));
console.log(user.upVotedPosts);
});
You dont need to explicitly push, since you pushed using findOneandUpdate - $push
Refer here
Secondly , its
user.save()
and not
User.save
First of all, I'd like to thank everyone's' help ;-)
I finally managed to get it partially working! My problem was that my functions were running asynchronously, causing some problems. I solved this by adding callback functions to each mongoose function.
However, the same error is still being returned, causing the server to crash. Everything else works; the new item is added to the array.
Is there anyway to ignore the error so that the server doesn't crash?
I have defined a schema like
var UserSchema = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
location: { type: String, required: true },
picture: { type: String, required: true },
passwordHash: { type: String, required: true },
resetPasswordToken: String,
resetPasswordExpired: Boolean
});
I have a REST Endpoint which return list of all users. In that list I want to hide some properties i.e, passwordHash, resetPasswordToken, resetPasswordExpired
I defined a custom filter function like below
var doFilterUser = function(user) {
_.omit(user, ['passwordHash', 'resetPasswordToken', 'resetPasswordExpired']);
user.id = user._id;
delete user._id;
delete user.__v;
return user;
};
_ is lodash
When I check my API is responding with all user properties
This filter function is defined in common helper module and I am calling it like
User.findOne({_id: id}, function(err, user) {
var filtered = helper.doFilterUser(user);
});
How to resolve this issue?
Try this:
You are allowed to access certain values through mongoose.
User.findOne({_id: id}, 'firstName lastName email location picture', function(err, user){
console.log(user);
});
You just mention the fields needed, after the query.
Hope it helps....
The problem here is that you still have a mongoose document that conforms to s strict schema. If you want to change that document, then you need to make it a "raw" object without all the additional controls:
User.findOne({_id: id}, function(err, user) {
var filtered = helper.doFilterUser(user.toObject());
});
So the .toObject() method here will return an object in it's raw form. That allows you to manipulate the keys how you wish.
You can also explicitly direct it not to serve back certain properties. Useful if you don't want to render a hashed password over the wire. The find method would look like this:
User.find({}, '-id -__v',function(err,users){
})
or
User.findOne({_id: id}, '-id -__v',function(err,user){
})
I am using sequelize in my application. I have postgres as underlying database.
But when I tried to save instances I got following error
[error: missing dimension value]
I have the following model
module.exports = function(sequelize, DataTypes) {
var Mymodel = sequelize.define('Mymodel', {
id: {type : DataTypes.INTEGER, autoIncrement : true, primaryKey: true},
title: {
type: DataTypes.STRING(128),
validate: {
notNull: true,
notEmpty: true
}
},
tags: DataTypes.ARRAY(DataTypes.TEXT)
});
return Mymodel;
}
I am sending http post request as
{
"title":"Test challenge",
"tags" : "['JAVA','REST','API']"
}
I am saving object like this
Mymodel.create(model).success(function(model) {
callback(null, challenge);
}).error(function(err) {
callback(err, null);
});
I tried sending over your model object as you stated and did get the error SequelizeValidationError: "['JAVA','REST','API']" is not a valid array. Perhaps you got a different error on an older version of Sequelize. Then, I made sure the tags value was a JavaScript array instead of a string and it worked.
Mymodel.create({
title: 'Test challenge',
tags: ['JAVA','REST','API']
}).then(function() {});
I'm trying to create a Meteor method to save the user profile from a form created by autoform. I'm getting an error saying the userSchema is not defined. It is defined in my helper which is within a Meteor.isClient condition, which could be the problem. I tried making it available to both the client and server but that didn't work.
What I'm trying to acheive is simply take the form values and insert them into the Meteor.users.profile.
Looks like the server isn't seeing the userSchema which is visible on the client.
I'm getting this error:
I20140816-14:14:28.170(-7)? Exception while invoking method 'saveProfile' ReferenceError: userSchema is not defined
I20140816-14:14:28.173(-7)? at Meteor.methods.saveProfile (app/server/server.js:6:16)
I20140816-14:14:28.173(-7)? at maybeAuditArgumentChecks (packages/livedata/livedata_server.js:1487)
I20140816-14:14:28.173(-7)? at packages/livedata/livedata_server.js:643
I20140816-14:14:28.173(-7)? at _.extend.withValue (packages/meteor/dynamics_nodejs.js:56)
I20140816-14:14:28.174(-7)? at packages/livedata/livedata_server.js:642
I20140816-14:14:28.174(-7)? at _.extend.withValue (packages/meteor/dynamics_nodejs.js:56)
I20140816-14:14:28.176(-7)? at _.extend.protocol_handlers.method (packages/livedata/livedata_server.js:641)
I20140816-14:14:28.176(-7)? at packages/livedata/livedata_server.js:541
My Schema:
if (Meteor.isClient) {
Schema = {};
Schema.UserProfile = new SimpleSchema({
firstName: {
type: String,
regEx: /^[a-zA-Z-]{2,25}$/
},
lastName: {
type: String,
regEx: /^[a-zA-Z]{2,25}$/
},
gender: {
type: String,
allowedValues: ['Male', 'Female']
},
bio: {
type: String,
},
avatar: {
type: String,
},
pinCode: {
type: Number,
min: 7,
max: 7
},
phoneNumber: {
type: Number,
min: 9,
max: 10
}
});
Schema.User = new SimpleSchema({
_id: {
type: String,
regEx: SimpleSchema.RegEx.Id,
optional: true,
},
email: {
type: String,
regEx: SimpleSchema.RegEx.Email,
optional: true,
},
createdAt: {
type: Date,
optional: true
},
profile: {
type: Schema.UserProfile,
},
services: {
type: Object,
optional: true,
blackbox: false
}
});
SimpleSchema.debug = true;
Meteor.users.attachSchema(Schema.User);
}
Here's my helper:
Template.signupForm.helpers({
users: function () {
return Meteor.users;
},
userSchema: function () {
console.log('returning user schema')
console.log(Schema.User)
return Schema.User;
}
});
My Meteor method (server.js):
Meteor.methods({
saveProfile: function(doc) {
console.log('Meteor method 1')
// Important server-side check for security and data integrity
check(doc, userSchema);
console.log('Meteor method')
console.log(doc.firstName)
}
});
My template
<template name="signupForm">
<div class="panel-body">
{{#autoForm schema=userSchema id="signupForm" type="method" meteormethod="saveProfile"}}
<fieldset>
{{> afObjectField name='profile'}}
</fieldset>
<button type="submit" class="btn btn-primary">Insert</button>
{{/autoForm}}
</div>
</template>
Please apply 2 steps :
1 :
Add Schema object (wih all descendants) to dir (like folder both) where it will be visible for client and server.
2 :
On server side use Schema.User instead userSchema.
Note that userSchema is defined on client side in Template.signupForm.helpers and because of that Meteor.methods.saveProfile cannot find it.