Unable to create a document using a model in Mongoose - node.js

I'm trying to create a REST api using express and mongoose. Below is the code for User model (user.server.model.js).
const mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
name: {
first: { type: String, required: true },
last: { type: String, required: true }
},
loginId: { type: String, required: true, unique: true },
password: { type: String, required: true },
location: String,
meta: { age: Number, website: String },
isActive: Boolean,
createdOn: { type: Date, default: Date.now },
updatedOn: Date
});
var User = mongoose.model('User', userSchema);
exports.User = User;
I'm trying to use this User model in express route (routes.js) as below:
const express = require('express'),
User = require('../models/user.server.model'),
router = express.Router();
router.route('/users')
.post((req, res) => {
let user = new User({
name: req.body.name,
loginId: req.body.loginId,
password: req.body.password,
location: req.body.location,
meta: req.body.meta,
createdOn: req.body.createdOn,
updatedOn: req.body.updatedOn
});
user.save((err) => {
if (err) {
res.send(err);
}
else{
res.json({ message: 'User created' });
}
});
});
module.exports = router;
But when I try to test this api using Postman extension in Chrome I'm getting below error
TypeError: User is not a constructor
Node Version: 6.0
Can anyone please advise whats going wrong here.

You're using the require value directly as User, so you should change exports.User to module.exports in user.server.model.js:
module.exports = User;

Related

Implementing text search with Mongoose

I want to implement text search on my app, and find documents where the field login matches the searched term,
I did the code below and I have no errors but the result in the route is always an empty array, there must be an error somewhere
Model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
created_at: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
display_name: {
type: String,
required: true,
index: true,
},
login: {
type: String,
required: true,
index: true,
},
});
UserSchema.index({ login: "text", display_name: "text" });
User = mongoose.model("users", UserSchema);
User.createIndexes();
module.exports = User;
Route
router.post("/users", async function (req, res) {
const { search } = req.body;
const users = await User.find({ $text: { $search: search } });
res.send(users);
});

Having an issue getting user id

So I am working on building a web app and I have a lot of it working. However I am trying to link my user._id to my items database. But when I try to post an item using postman the app crashes saying it cant read property '_id' of null. I know I am missing something but I honestly can't figure out what other code I need to implement. Any help would be great. Thanks
Here is the code for the UserSchema:
const mongoose = require('mongoose');
const passportLocalMongoose = require("passport-local-mongoose");
const UserSchema = new mongoose.Schema({
username: {
type: String,
trim: true,
unique: true,
required: true,
minlength: 3,
maxlength: 15
},
firstName: {
type: String,
required: true,
minlength: 3,
maxlength: 15
},
lastName: {
type: String,
required: true,
minlength: 3,
maxlength: 15
},
email: {
type: String,
unique: true,
required: true
},
resetPasswordToken: String,
resetPasswordExpires: Date,
isAdmin: {
type: Boolean,
default: false
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("user", UserSchema);
Here is the code for the ItemSchema:
const mongoose = require('mongoose');
const User = require('./user');
const ItemSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 3,
maxlength: 20
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
createdBy: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("items", ItemSchema);
And here is the code for the route thats throwing the error:
const express = require("express");
const router = express.Router();
const User = require("../models/user");
router.route("/item/add")
.post(function(req, res) {
User.findById(req.user._id, function(user, err) {
if (err) {
console.log(err);
}
var item = new Item();
item.name = req.body.name;
item.description = req.body.description;
item.price = req.body.price;
item.createdBy = { id: req.user._id, username: req.user.username };
item.save(function(err) {
if (err) {
res.send(err);
}
res.json({ message: "Item was successfully saved" });
console.log(item);
});
});
});
You need to send your data in json format in postman for example:
{'id':1, 'name':'jhon doe', 'email':'jhondoe#example.com'}
in your backend file you need to call
req.body.id not req.user._id

Mongoose model not saving for some reason

I've create a Mongoose model and I wrote some code to test if it works, I tried to save the model and then display all of the models but it doesn't log anything to the console and the model isn't saving.
My testing code:
let User = require('./models/user')(MAI);
let myUser = new User({
username: 'Admin',
email: 'admin#example.com',
password: '123456',
});
await myUser.save();
User.find((err, users) => {
if(err) console.log(err);
console.dir(users);
});
My model:
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
user_id: Number,
username: String,
email: String,
password: String,
verified: { type: Boolean, default: false },
joindate: { type: Date, default: Date.now },
postcount: { type: Number, default: 0 },
});
module.exports = function(MAI) {
UserSchema.plugin(MAI.plugin, {
model: 'User',
field: 'user_id',
startAt: 1,
incrementBy: 1,
unique: true
});
return mongoose.model('User', UserSchema);
}
And if it's important, mongoose & mai initialization:
mongoose.Promise = require('bluebird');
let connection = mongoose.createConnection('mongodb://localhost:27017/forum');
MAI.initialize(connection);
Fixed it, the problem was I required mongoose in the model file when what I should've done was to pass the mongoose from my entry point.

Getting all Posts that belong to one User and display to pass to the view Node / Express / Mongoose

Below is the code for User model, Post model and the route. I need to query the DB and then pass to the view through the router. What am I missing?
User model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
Posts model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new Schema({
postTitle: {
type: String,
required: true
},
postStory: {
type: String
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model('Post', postSchema);
And here is the query in the router that I'm trying but apparently it's not the way to go...
My GET route:
router.get('/dashboard', isLoggedIn, function(req, res) {
Post.find({author:req.user._id}, (err, posts) => {
if(err) {
console.log(err);
} else {
res.render('users/dashboard', {currentUser: req.user, posts: posts});
}
});
});
What am I missing here?
You may want to change the find query to match the proper attribute in the following line:
Post.find({author: req.user._id}, (err, posts) => {
to be:
Post.find({'author.id': req.user._id}, (err, posts) => {
Read more: http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html

Getting all posts that belong to one user in Node / Express

I have 2 models User & Revive as you can see below... in the router(see below) what is the query to get all revives that belong to the user/creator to display on his dashboard/profile page?
User Model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
Revive Model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var reviveSchema = new Schema({
reviveTitle: {
type: String,
required: true
},
reviveStory: {
type: String
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
}
});
module.exports = mongoose.model('Revive', reviveSchema);
Router:
router.get('/dashboard', isLoggedIn, function(req, res) {
code ?? to get all revives that belong to the creator/user only ??
res.render('users/dashboard', {currentUser: req.user});
});
Well, I would setup the Revive schema bit differently:
author: { type: mongoose.Schema.Types.ObjectId, ref: "User"}
Then you should be able to just do a proper find:
const Revive = mongoose.model('Revive');
router.get('/dashboard', isLoggedIn, function(req, res) {
Revive.find({author:req.user._id}, (e, revives) => {
// however you handle errors goes first
res.render('users/dashboard', {currentUser: req.user, revives: revives});
});
});

Resources