0

I try to save the some information in to Mongo with Mongoose, but nothing happens… My code is :

function User() { console.log(_db.version); var user_schema = new _db.Schema({ 'email': { 'type': String, 'required': true, 'lowercase': true, 'index': { 'unique': true } }, 'password': { 'type': String, 'required': true }, 'name': {'type': String, 'required': true}, 'age': {'type': Date}, }, {'collection': 'users'}); var user_model = _db.model('user', user_schema); this.createNew = function(name, age) { console.log('createNew'); var new_user = new user_model({'name': name, 'age': age}); new_user.save(function(err){ console.log(err); console.log('Save function'); }); } } var user = new User(); user.createNew('Tom', 21); 

In the result i just get 3.8.1 createNew.

4
  • 3
    new User() instead of User() Commented Dec 29, 2013 at 16:23
  • this in this.createNew won't be what you want if you don't use new to create User. Commented Dec 29, 2013 at 16:31
  • with object creation is everything ok, in the program everything quite differently, the problem is that new_user.save doest fire. Commented Dec 29, 2013 at 16:58
  • @Kin please mark the answer you think is correct.. Commented Sep 15, 2014 at 18:00

2 Answers 2

2

I suggest you change your approach a bit, try this out:

var UserSchema = new Schema({ email: { type: String, required: true, lowercase': true, index: {unique: true}, }, password: {type: String, required: true}, name: {type: String, required: true}, age: {type: Date}, }) UserSchema.statics.createNew = function(email, password, name, age, next) { var user = new this({ email: email, password: password, name: name, age: age }) user.save(next) } mongoose.model('User', UserSchema) 

Now you can create a new User by:

var User = mongoose.model('User') User.createNew('[email protected]', 'password', 'Tom', 21, function(err, user) { ... }) 

Added email and password as arguments because the Schema says that they are required.

Sign up to request clarification or add additional context in comments.

1 Comment

This still would not work, since "password" and "email" are required as shubhank srivastava mentioned.
1

I don't see you assigning values to email and password fields of the schema.

required: {Boolean} - If true, creates a validation rule requiring this path be set before saving occurs.

http://mongoosejs.com/docs/2.7.x/docs/schematypes.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.