When I submit my content it shows ERR_EMPTY_RESPONSE. In my node console, it shows me the Error: RangeError: Maximum call stack size exceeded. When I restart my server message content field will show. In my database, the message model has content value but users model has no message id.
I am using Mongoose 5.0.0.
when check my db it shows messages=[]
db.users.find()
{ "_id" : ObjectId("5a771f08ee207b13808a2599"), "firstName" : "rakib", "lastName" : "vai", "password" : "$2a$10$kCGCyFOPCedZcs.4Y6D.Huq02aYycuEssj5suTh00bRJSCGw1N3VO", "email" : "xxxxxx#gmail.com", "messages" : [ ], "__v" : 0 }
In my messages collection show like this
db.messages.find()
{ "_id" : ObjectId("5a771f20ee207b13808a259a"), "content" : "rakibvai", "user" : ObjectId("5a771f08ee207b13808a2599"), "__v" : 0 }
My message model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user');
var schema = new Schema({
content: {type: String, required: true},
user: {type: Schema.Types.ObjectId, ref: 'User'}
});
schema.post('remove', function (message) {
User.findById(message.user, function (err, user) {
user.messages.pull(message);
user.save();
});
});
module.exports = mongoose.model('Message', schema);
And my user model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
messages: [{type: Schema.Types.ObjectId, ref: 'Message'}]
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('User', schema);
my message.js route
router.post('/', function (req, res, next) {
var decoded = jwt.decode(req.query.token);
User.findById(decoded.user._id, function (err, user) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
var message = new Message({
content: req.body.content,
user: user
});
message.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
user.messages.push(result);
user.save();
res.status(201).json({
message: 'Saved message',
obj: result
});
});
});
});
Related
I want to use mongoose discriminator for my project to create a collection of users in which there is a document of owner which I want to implement using discriminators. But I am getting an error of
throw new Error('The 2nd parameter to mongoose.model() should be a ' +
^
Error: The 2nd parameter to mongoose.model() should be a schema or a POJO
at Mongoose.model (D:\Github\Food-Delivery-Website\node_modules\mongoose\lib\index.js:473:11)
at Object. (D:\Github\Food-Delivery-Website\models\Owner.js:21:27)
Code is given below:
// This file is models/User.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const options = { discriminatorKey: 'kind' };
const UserSchema = new Schema(
{
userName: {
type: String,
required: true,
unique: true,
},
restOwned: {
// type: [Schema.Types.ObjectId],
type: Number,
},
},
options,
);
module.exports = mongoose.model('User', UserSchema);
Below is the next file
// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const User = require('./User');
const OwnerSchema = User.discriminator(
'Owner',
new Schema({
isOwner: {
type: Boolean,
required: true,
},
restName: {
type: String,
required: true,
},
}),
);
module.exports = mongoose.model('Owner', OwnerSchema);
Then I import these two files in userController.js
//This file is controllers/userController.js
const User = require('../models/User');
const Owner = require('../models/Owner');
exports.addUser = async (req, res) => {
try {
const newUser = new User({
userName: req.body.userName,
restOwned: req.body.restOwned,
});
const user = await newUser.save();
res.status(201).json({
status: 'Success',
user,
});
} catch (err) {
res.status(500).json({
status: 'failed',
message: 'Server Error: Failed Storing the Data.',
err,
});
}
};
exports.addOwner = async (req, res) => {
try {
const newOwner = new Owner({
isOwner: req.body.isOwner,
restName: req.body.restName,
});
const owner = await newOwner.save();
res.status(201).json({
status: 'Success',
owner,
});
} catch (err) {
res.status(500).json({
status: 'failed',
message: 'Server Error: Failed Storing the Data.',
err,
});
}
};
What am I doing wrong here?
enter image description here
The Model.discriminator() method returns a Model.
So you can directly export the discriminator and use it as the model
// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const User = require('./User');
//Directly export the discriminator and use it as the model
module.exports = User.discriminator(
'Owner',
new Schema({
isOwner: {
type: Boolean,
required: true,
},
restName: {
type: String,
required: true,
},
}),
);
//module.exports = mongoose.model('Owner', OwnerSchema);
I am trying to read data from the mongo database , but I am getting error.
I will explain what I did.
create two schema
let CompanySchema = new Schema({
name: {type: String, required: true, max: 100},
contactPerson: {type: String},
});
// Export the model
module.exports = mongoose.model('Company', CompanySchema);
let UserSchema = new Schema({
name: {type: String, required: true, max: 100},
companyId:{ type: Schema.Types.ObjectId, ref: 'companyId' }
});
// Export the model
module.exports = mongoose.model('UserTest', UserSchema);
First, add one company like this.which is successfully added
app.get('/addCompany', async (req, res) => {
let company = new Company({
name: 'Test 1',
contactPerson: 'rajesh'
})
company.save(function (err) {
if (err) {
console.log(err);
res.status(500).send(err);
// return next(err);
}
res.send('company added successfully')
//res.render('index', { title: 'Express'})
});
})
Then I added a user like this .which is successfully added.
app.get('/addUser', async (req, res) => {
let user = new User({
name: 'Test 1',
companyId: '5d3d46b2825d7f0eaf9d9d27'
})
user.save(function (err) {
if (err) {
console.log(err);
res.status(500).send(err);
// return next(err);
}
res.send('user added successfully')
//res.render('index', { title: 'Express'})
});
})
Now I am trying to fetch all user with company detail and getting error
app.get('/getUser', async (req, res) => {
User
.find({})
.populate('companyId') // only works if we pushed refs to person.eventsAttended
.exec(function(err, data) {
if (err) {
console.log(err)
return;
}
res.send(data);
});
})
error
MissingSchemaError: Schema hasn't been registered for model "companyId".
Use mongoose.model(name, schema)
at new MissingSchemaError (/Users/b0207296/WebstormProjects/untitled2/node_modules/mongoose/lib/error/missingSchema.js:22:11)
at NativeConnection.Connection.mode
Can you try now after changing your second schema to this :
let UserSchema = new Schema({
name: {type: String, required: true, max: 100},
companyId:{ type: Schema.Types.ObjectId, ref: 'Company' }
});
module.exports = mongoose.model('UserTest', UserSchema);
Assuming companyId's has matching documents in _id's of Company. Similar kind of functionality can also be achieved thru $lookup of mongoDB.
in ref you should pass the Company instead of company id
let UserSchema = new Schema({
name: {type: String, required: true, max: 100},
companyId:{ type: Schema.Types.ObjectId, ref: 'Company' }
});
my objective is to push a message into the messages property (which is an array) of a user object using Mongoose. However, I get an error when I try to save the user (user.save()). I did these three console.logs on the code below to see what went wrong. Can someone fix this?
console.log(user.messages);
user.messages.push(result._id);
console.log(user.messages)
user.save(function (err, result) {
console.log(err)
});
So, one before I push the message into the array, one right after and one to check the error after I tried to save the user. This gave me the following logs:
first, an empty array
[]
second, an array containing the message ID
["5a5cdd894504771c80c8901a"]
Third, the error why it didn't save the user properly:
{ MongoError: Unknown modifier: $pushAll
at Function.MongoError.create (C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb-core\lib\error.js:31:11)
at toError (C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb\lib\utils.js:139:22)
at C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb\lib\collection.js:1059:67
at C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb-core\lib\connection\pool.js:469:18
at process._tickCallback (internal/process/next_tick.js:150:11)
name: 'MongoError',
message: 'Unknown modifier: $pushAll',
driver: true,
index: 0,
code: 9,
errmsg: 'Unknown modifier: $pushAll' }
This is the code on the server side (node.js)
router.post('/', function (req,res,next){
// We stored the user in the token so we can retrieve it from this token.
// fetch the user (in the token) who reached this route
// we use the jwt package to decode the token ( we wont be able to grab the user if we skip this step)
// the decode method does not check if the token is valid, this happens
// higher up in this file. we only decode it to grab the user. If we hadn't
// protected our route we wouldve had to use a different strategy (.verify method)
var decoded = jwt.decode(req.query.token);
User.findById(decoded.user._id, function(err, user){
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
var message = new Message({
content: req.body.content,
user: user._id
});
message.save(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
console.log(user.messages);
user.messages.push(result._id);
console.log(user.messages)
user.save(function (err, result) {
console.log(err)
});
res.status(201).json({
message: 'Saved message',
// this object is what we'll receive in the front-end
// and what we'll convert using the response.json() method
obj: result
});
});
});
});
This is the user Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
messages: [{type: Schema.Types.ObjectId, ref: 'Message'}]
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('User', schema);
according to this issue, $pushAll has beed deprecated, you can get around this by setting { usePushEach: true } in you schema options
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
messages: [{type: Schema.Types.ObjectId, ref: 'Message'}]
}, { usePushEach: true });
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('User', schema);
hi I wanna see on the screen User all information but I cannot add user in mongodb . User's location information in Locations Schema.But I dont know how to get location information(i.e city,town...) to input UserSchema.This is my codes:
User Schema :
var userSchema = Mongoose.Schema({
name:{type: String,require:true},
surname: {type: String,require:true},
tel: {type: String,require:true},
age: {type: String,require:true},
mevki_id: {type: String,require:true},
location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' }
});
Create User Function :
this.createUser = function (req, res, next) {
var lok=new Location({il:req.params.il,ilce:req.params.ilce});
lok.save(function(err){
var user=new User({name:req.params.name,surname:req.params.surname,tel:req.params.tel,age:req.params.age,mevki_id:req.params.mevki_id,location_id:user});
user.save(function(err){
user.location_id=lok;
});
return res.send({})
});
}
Thnks :)
//define this as your schema in your file
var userSchema = new Schema({
name: {type: String, required: true},
surname: {type: String, required: true},
tel: {type: Number, required: true},
age: {type: Number, required: true},
mevki_id: {type: String, required: true},
location_id:{type:String,required:true}
});
var CollectionModel_user = conn.model('users', userSchema)
return function (req, res, next) {
req.Collection_user = CollectionModel_user;
next();
}
// create a route which can create a route in your
// app.js or main.js file that will create a new
// collection in your mongo.
router.all('/user/create', function (req, res) {
var create = req.Collection_user;
var name = req.body.name;
var surname = req.body.surname;
var tel = req.body.tel;
var age = req.body.age;
var mevki_id = req.body.mevki_id;
var location_id = req.body.location_id;
var record = new create({
name: name,
surname: surname,
tel: tel,
age: age,
mevki_id: mevki_id,
location_id: location_id
});
if (name.length > 0) {
record.save(function (err, result) {
if (err) {
res.json({status: 0, message: err})
} else {
res.json({status: 1, message: " success"});
}
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});
So I am trying to hide the password object from showing. Here's my code, I am using bcrypt to ash the password. I am hiding the return objectBut I am not getting my expected results. What am I doing wrong, please help. Greatly appreciate it.
Thanks.
var express = require('express')
var router = express.Router()
var User = require('../Models/User.js')
var bcrypt = require('bcrypt')
router.get('/:resource', function(req, res, next){
var resource = req.params.resource
if (resource == 'user'){
User.find(null, function(err, users){
if(err) {
res.json({
confimration: 'error',
message: err
})
return
}
res.json({
confimration: 'success',
message: users
})
return
})
}
})
router.post('/:resource', function(req, res, next){
var resource = req.params.resource
var data = req.body
var password = data.password
var hashed = bcrypt.hashSync(password, 10)
data['password'] = hashed
if(resource == "user") {
User.create(data, function(err, user){
if(err){
res.json({
confirmation: 'fail',
message: err
})
return
}
res.json({
confirmation: 'success',
result: user
})
return
})
}
})
module.exports = router
var mongoose = require('mongoose')
var UserSchema = new mongoose.Schema({
firstName: {type: String, lowercase: true, trim: true, default: ''},
lastName: {type: String, lowercase: true, trim: true, default: ''},
email: {type: String, lowercase: true, trim: true, default: ''},
city: {type: String, default: ''},
password: {type: String, default: ''},
timestamp: {type:Date, default: Date.now}
})
UserSchema.methods.summary = function() {
var summary = {
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
timestamp: this.timestamp,
id: this._id,
city: this.city
}
return summary
}
module.exports = mongoose.model('UserSchema', UserSchema)
{
_id: "57f460235805b52762605df2",
__v: 0,
timestamp: "2016-10-05T02:06:27.829Z",
password: "$2a$10$DIHrMO8WcRmOkIVj93SSQ.LFe5vPYH6R3xrfsSuql.v2jfU2mcO.C",
city: "new york",
email: "4",
lastName: "4",
firstName: "4"
}
for the router.get you could use a projection field. I don't know why you have null. but this find searches for all the docs in users collection and excludes the password field for each doc returned. does this help with the router.get?
if (resource == 'user'){
User.find({},{password: 0}, function(err, users){
if(err) {
res.json({
confimration: 'error',
message: err
})
return
}
res.json({
confimration: 'success',
message: users
})
return
})
}