In my app.js I require my model like
var User = require('./models/user');
app.post('/user/add', function(req,res,next){
var newUser = new User();
newUser.add(req.body.name, function(response){
res.json(response);
})
});
and my model (user.js) look like this
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String
});
var User = module.exports = mongoose.model('user', userSchema);
module.exports.add = function(name,callback){
User.save({name:name}).exec(callback);
}
But I got error of newUser.add is not a function?
If you want to add instance methods to a mongoose Model you should use instance methods syntax:
var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
name: String
});
// Instance methods
UserSchema.methods.add = function(name, callback){
this.name = name;
return this.save(callback);
}
module.exports = mongoose.model('User', UserSchema);
Methods can be added with methods keyword like this
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String
});
userSchema.methods.add = function(name,callback){
User.save({name:name}).exec(callback); // not checking logic
}
var User = module.exports = mongoose.model('user', userSchema);
You can do it as follows:
var mongoose = require('mongoose');
var Schema = Mongoose.Schema;
//schema is declared here
var userSchema = new Schema({
name: String
});
var user = Mongoose.model('User', UserSchema);
//here we are assigning new data to user collection
//this record will not be saved here
//it will only check the schema is matching or not
//if record is matching to schema then it will assign '_id' to that record
var userRec = new user({"name":"Jessie Emerson"});
userRec.save(function(error, userDoc) {
//this is the callback function
});
If you need anymore clarifications then please comment on this answer. :-)
Related
I am trying to save a user to mongodb database using post request as follow, but I got the error TypeError: User is not a function. It's a pretty simple set up of the code but i can't figure out anything wrong with it.
I am using:
mongoose 4.8.6
express 4.15.2
node 6.6
// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String
});
// server.js
var User = require('./models/user');
app.post('/create-user', function(req, res, next) {
var user = new User(); // TypeError: User is not a constructor
user.email = req.body.email;
user.password = req.body.password;
user.save(function(err) {
if (err) return next(err);
res.json('Successfully register a new user');
});
});
You need to create model from your UserSchema and then export it, then you can create new User objects.
// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String
});
module.exports = mongoose.model('User', UserSchema)
You got that error because you exported the modules wrongly,
In my case in the models/user I had written module.export leaving out the s at the end
When you run the code it then gives you that error
I would advice checking on your module.exports = mongoose.model('User', UserSchema) spellings
// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String
});
var User = mongoose.model('User', UserSchema)
module.exports = { User } <-- capital 'U'
Changing the lowercase user variable into uppercase (like below) strangely worked:
const User = mongoose.model('users');
I really thought this was just a best practice but eventually, seems to be mandatory.
Change this var user = new User(); for this var User = new User();
I was also facing the same error but this worked for me.
I did change my export file
var User = mongoose.model('User',userSchema);
module.exports = {User};
To
module.exports = mongoose.model('User', userSchema);
Cannot overwrite partnerCode model once compiled.
I have a file like models/partnerCode.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var partnerCodeSchema = new Schema({
email: String,
used: {type: Number, default: 0}
});
var partnerCode = module.exports = mongoose.model('partnerCode', partnerCodeSchema);
module.exports.add = function(code){
partnerCode.findOne({email:code},function(err,response){
console.log(response);
});
}
and in my app.js I try to add an end point to make rest POST
var PartnerCodeModel = require('./models/PartnerCode');
app.post('/PartnerCodeModel/add', PartnerCodeModel.add( function(req,res,next){
console.log('code: '+req.body.code);
}))
Above code won't work, I got Cannot overwrite partnerCode model once compiled why ?
It should work like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var partnerCodeSchema = new Schema({
email: String,
used: {type: Number, default: 0}
});
var partnerCode = mongoose.model('partnerCode', partnerCodeSchema);
module.exports.add = function(code){
partnerCode.findOne({email:code},function(err,response){
console.log(response);
});
}
If you need any further assistance then comment on this answer. I would like to help you. :-)
I'm making a node application. Users can have favorite Listings of rooms ( just like wish list). I'm trying to add listings ids to user favorite listings but that always gives undefined. if i do "console.log(users.favoriteListings);" the output comes to be undefined. Any help please.
listingModel.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;//creating schema
var ListingSchema = new Schema({
location: {//ROOM LOCATION
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
},
}
);
var Listing = mongoose.model('Listing', ListingSchema);
module.exports = Listing;
userModel.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;//creating schema
var Listing=require('../listing/listingModel');
var UserSchema = new Schema({
favoriteListings : [{ type: Schema.Types.ObjectId, ref: 'Listing' }],
}
);
var User = mongoose.model('User', UserSchema);
module.exports = User;
userController.js
addFavListing:function(req,res){
//READ TOKEN AND FIND USER ID, IF USER HAS REACHED THIS POINT, THIS MEANS THAT TOKEN ALREADY
//HAS BEEN VERIFIED
var token = req.body.token || req.query.token || req.headers['x-access-token'];
var decoded=jwt.verify(token, app.get('superSecret'));
var id=decoded._doc._id;console.log(id);
User.find({_id:id}).populate('favoriteListings').exec(function(err,users) {
if (err){ return handleError(err);}
console.log(users.favoriteListings);
});
You got an array of users from mongoose.
This array has no favoriteListings property.
But each user in the array must have his favoriteListings.
In your userController, try to replace the console.log by this one:
console.log(users.forEach(function(user) {
console.log(user.favoriteListings);
}));
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
});
Hi There: I'm having a difficult time online finding out how to perform a simple database connection, schema creation, and basic CRUD using mongoose with node.js. Right now I have the following code but am getting the error:
"TypeError: object is not a function
at Schema.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native).."
// Launch express and server
var express = require('express');
var app = express.createServer();
//connect to DB
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/napkin_0.1');
// Define Model
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
User = new Schema({
'title': { type: String, index: true },
'data': String,
'tags': [String],
'user_id': ObjectId
});
//Define Collection
mongoose.model('Document', User);
var user = new User();
user.title = "TEST TITLE";
user.save();
//Launch Server
app.listen(3002);
You are trying to instantiate an instance of the Schema. I would change
User = new Schema({
To
UserSchema = new Schema({
and later on call
var User = mongoose.model('user', UserSchema);
and finally
var user = new User();
After your schema definition.
//Define Collection
mongoose.model('Document', User);
The above code is not for defining collection, it is to initialize the model object.
Change it as follows:
//Create Model Object
var UserModel = mongoose.model('user_model_name', User); // 2nd param -> User is a schema object
Then create the Document object out of model object.
As follows:
var user_doc = new UserModel();
Then you can use getters/setters and methods.
user_doc.title = 'your text for title';
user_doc.save();