It's my first time using Mongoose and the save function is not working for me...
On user model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = mongoose.model('User', {
name: Schema.Types.Mixed,
gender: String,
email: String
});
module.exports = User;
On my user controller file:
// Create a user
router.post('/', function(req, res) {
var user = new User(req.body);
user._id = mongoose.Types.ObjectId();
user.save(function(err) {
if (err) {
return res.status(500).json({
error: "Error creating user: " + err
});
}
return res.status(200).end();
});
});
I tried everything but I can't save the user object to the database: "id is not defined"
On the db the _id is a ObjectId.
Thanks.
mongoose.model receives collection name and a Schema as arguments, not an regular object.
So you should use the following code instead:
var schema = new mongoose.Schema({
name: Schema.Types.Mixed,
gender: String,
email: String
});
var User = mongoose.model('User', schema);
maybe we can change the code structure && remove "user._id", test please this code :
*model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: Schema.Types.Mixed,
gender: String,
email: String
});
module.exports = mongoose.model('User', UserSchema);
*controller file:
// Create a user
router.post('/', function(req, res) {
var user = new User(req.body);
user.save(function(err) {
if (err) {
return res.status(500).json({
error: "Error creating user: " + err
});
}
return res.status(200).end();
});
});
Related
I'm making a simple example of CRUD for a larger and open source project. Right now I want to populate with user data, I have already looked at the documentation and some forums and I am not able to solve the problem that is causing here.
The message in terminal "Populated User undefined"
Could anyone help?
userModel
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: {
type: String
},
});
userController
var mongoose = require('mongoose'),
User = mongoose.model('Users');
exports.create_a_user = function(req, res) {
var new_user = new User(req.body);
new_user.save(function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
msgModel
module.exports = mongoose.model('Users', userSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var msgSchema = new Schema({
title: {
type: String
},
body: {
type: String
},
created_date: {
type: Date,
default: Date.now
},
user : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
});
module.exports = mongoose.model('Messages', msgSchema);
msgController
var mongoose = require('mongoose'),
Message = mongoose.model('Messages');
exports.list_all_messages = function (req, res) {
Message.find({})
.populate('user')
.exec((err, msg) => {
if (err)
res.send(err);
res.json(msg);
});
};
module.exports = mongoose.model('Users', userSchema);
maybe in msgSchema you have to reference 'users' instead of 'user'
So, I found the error in the code, in the user's schema there was a lack of reference to the export of the name that was placed in the user's model.
user : {
type: mongoose.Schema.Types.ObjectId,
ref: 'Users'
},
So,...
module.exports = mongoose.model('Users', userSchema);
I am working on a test signup with nodejs, i set up a free mongo lab database and testing signups on my local server. i keep getting this error an on my route, i can console upto var user = new User(); (console- user) and get the objects . I can console user.profile and console will display name and picture as objects etc. but for some reason my code is saying user.profile.name is undefined . Any error you guys can spot ?
this is my model
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var UsersSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String,
profile: {
name: { type: String, default: '' },
picture: { type: String, default: '' }
},
address: String,
history: [{
date: Date,
paid: { type: Number, default: 0 },
}]
});
UsersSchema.pre('save',function(next){
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt){
if(err) return next(err);
bcrypt.hash(user.password,salt, null,function(err,hash){
if (err) return next(err);
user.password = hash;
next();
});
})
})
UsersSchema.methods.comparePassword = function(password){
return bcrypt.compareSync(password, this.password)
}
module.exports = mongoose.model('User',UsersSchema);
this my route file
var router = require('express').Router();
var User = require('../models/users');
// var user = new User();
// console.log('user',user.profile.name);
router.post('/signup', function(req, res, next) {
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
User.findOne({ email: req.body.email }, function(err, existingUser) {
if (existingUser) {
return res.redirect('/signup');
} else {
user.save(function(err, user) {
if (err) return next(err);
res.json("New user has been created");
});
}
});
});
module.exports = router;
//res.json("New user has been created")
You'll have to assign profile to something first as user is defined but user.profile is not
defined user.profile = '' before the line user.profile.name = req.body.name
or replace the following and try
-var User = require('../models/users'); with var UsersSchema = require('../models/users');
-var user = new User(); with var user = new UsersSchema();
You are trying to access name property from profile, which is not defined.
var user = new User();
user.profile.name = req.body.name;
-----------/\
To make this work, first define profile:
var user = new User();
user.profile = {};
user.profile.name = req.body.name;
I'm trying to find a user in my node app with mongoose by using
var User = require('../app/models/user');
function mongoTest() {
var publicAddress = "0x8a6be8979340faa30020b0c1f617d8fd4309679f";
User.findOne({"publicAddress": publicAddress}, (err, user) => {
if (err) {
res.status(500).send(err)
} else {
console.log(user);
}
});
}
and err and user always return null. From other questions here (this and this), this usually seems to be related to mongoose pluralising collections. However, I don't think that's my issue because my users.js has
module.exports = mongoose.model('User', userSchema);
// Have also tried module.exports = mongoose.model('User', userSchema, 'User');
For completeness, users.js is
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// Define the schema for our user model
var userSchema = mongoose.Schema({
local: {
username: String,
password: String,
pictureCaption: String,
publicAddress: String,
contractAddress: String
}
});
Finally, I'm sure that public address exists because I can see it in the mongoDB with Robo 3T.
In your userSchema the publicAddress is part of local object.
var userSchema = mongoose.Schema({
local: {
username: String,
password: String,
pictureCaption: String,
publicAddress: String,
contractAddress: String
}
});
You are trying to find an object with publicAddress but it's actually inside the local object. So you should edit the query as follows to get the result.
User.findOne({"local.publicAddress": publicAddress}, (err, user) => {
if (err) {
res.status(500).send(err)
} else {
console.log(user);
}
});
I am using node and mongoose to build an app. And when testing, there exists a strange problem. Here is my auth.index.js(for user login).
auth.index.js:
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/environment');
var User = require('../api/user/user.model');
var jwt = require('jsonwebtoken');
var auth = require('./auth.service');
var router = express.Router();
router.post('/login', function (req, res, next){
User.find({email: req.body.email}, function (err, user){
if (err) {
return next(err);
} else if (!user) {
return res.json({message: 'Invalid email.'});
} else {
if(!user.authenticate(req.body.password)){
return res.json({message: 'Invalid password.'});
};
var token = auth.signToken(user._id, user.username, user.role);
return res.json({token: token});
};
});
});
Here is the user.model.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
password: String,
email: {type: String, lowercase: true},
role: {type: String, default: 'user'},
provider: String,
date: String
});
UserSchema.methods = {
//check password
authenticate: function(plainText) {
return plainText === this.password;
}
};
However, in the command window, it returns that
user.authenticat is not a function.
I wanna know why, and does it mean that I cannot use the method directly or I need to invoke the method through passport ? Thanks.
I think you have misplaced your methods. It should be like this.
UserSchema.methods.authenticate: function(plainText) {
return plainText === this.password;
}
See the following link for the complete example. https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications
the issue i'm having is that mongoose isn't letting me instantiate an object of a schema type, inside a 'pre' method, of a different schema.
I've got 2 schemas - 'User' and 'Tickit'.
User.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var Tickit = require('../models/Tickit');
var userSchema = new Schema({
email : String,
password : String,
tickits : [Tickit.tickitSchema]
});
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = mongoose.model('User', userSchema);
and Tickit.js
var mongoose = require('mongoose');
var User = require('../models/User');
var Schema = mongoose.Schema;
var tickitSchema = new Schema({
title: String,
description: String,
author : { type: Schema.Types.ObjectId, ref: 'User' },
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}]
});
tickitSchema.pre('save', function(next){
var user = new User();
user.tickits.push ({id:this._id});
user.save(function(err){
if(err)
res.send(err)
.populate('tickits')
.exec(function(err, blah){
if(err) res.send(err);
})
res.json(blah);
})
next();
})
module.exports = mongoose.model('Tickit', tickitSchema);
What i'm trying to do with the pre method in Tickit is populate the 'Tickits' array in the User schema with the id of that Tickit every time a Tickit is created.
However in my app when I do create a tickit, the app crashes and I get this error
var user = new User();
^
TypeError: object is not a function
Try to define user inside your function:
tickitSchema.pre('save', function(next){
var User = require('../models/User');
// Code
});