// controllers/users.js
'use strict';
var mongoose = require('mongoose'),
User = mongoose.model('Users');
exports.list_all_users = function(req, res) {
User.find({}, function(err, users) {
if (err)
res.send(err);
res.json(users);
});
};
// exports.list_all_users = function(req, res){
// res.send("display all users");
// };
exports.create_a_user = function(req, res){
res.send("user_created");
};
exports.delete_a_user = function(req, res){
res.send("user_deleted");
};
./routes/users.js
'use strict';
module.exports = function(app) {
var users = require('../controllers/users');
// users Routes
app.route('/users')
.get(users.list_all_users);
}
model/UserModel.js
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
_id:{
type : Number,
auto : true },
name: {
type : String,
required: 'Kindly enter the name '
},
password: {
type: String
},
email:{
type: String,
required: 'Kindly enter the mailId '
},
role:{
type: String,
required : 'Enter a valid role '
},
invitedBy: {
type: Number,
required : 'Valid number'
}
});
module.exports = mongoose.model('Users', UserSchema);
server.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
User = require('./model/UserModel'), //created model loading here
bodyParser = require('body-parser');
// mongoose instance connection url connection
var dbConfig = require('./db');
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.config);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var userRoutes = require('./routes/users'); //importing route
userRoutes(app); //register the route
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);
I tried printing 'display as respone' to response and it works, the database connection is successful.
But when I try to get from the db, it prints[] for /users get
I suspect something is wrong with my model
Can anyone point out what went wrong here ?
My collection:
collection : "Users"
{
"_id": 112,
"name": "abcd",
"password": "hash12341234",
"email": "questioner#hotmail.com",
"role": "musician",
"invitedBy": 1
}
In you controllers/user.js, you have tried to created a user model again. Can you try importing as follows,
var mongoose = require('mongoose'),
User = require('../model/UserModel')
In you userModel.js, you need to also place a connection string
var db = mongoose.connect("mongodb://localhost/XXXXX");
var Schema = mongoose.Schema;
You just need to replace a line in controller/user.js
Use:
User = require('../model/UserModel')
instead of:
User = mongoose.model('Users');
Hope this helps.
Actually, the issue is that, the get function is returning the objects in collection created only using the model in Node.
I tried creating the user with the api and tested get users but it works like charm.
I am still puzzled about why it is unable to return the objects from the collection which were created by me manually.
Related
route/signup.js
var express = require('express');
var router = express.Router();
const User = require('../model/user');
var mongoose = require('mongoose');
function userFind(value){
return User.find({user_id:value}).exec();
};
router.get('/',function (req,res) {
res.render('login/signup');
});
router.post('/',async function (req,res,next){
try{
let userid =req.body.id;
console.log(userid); //abcdefg
const user = await userFind(userid);
console.log(user); // []
}catch(err){
next(err);
}
})
module.exports = router;
model/user.js
const mongoose = require('mongoose')
var Schema = mongoose.Schema;
const userSchema = new Schema(
{ user_id : {type:String,required:true, unique:true},
user_password : {type:String, required:true, select:false},
user_name: {type:String, required:true},
user_email : {type:String,required:true,unique : true},
user_birth : {type:String,require:true},
},{versionKey:false},
{collection: 'user'}
);
module.exports = mongoose.model('user',userSchema);
data inside mongodb.
{
"_id": {
"$oid": "60413c7c48e5e61187cc4eeb"
},
"user_id": "abcdefg",
"user_password": "test111",
"user_name": "세글자",
"user_email": "test#naver.com",
"user_birth": "884455"
}
app.js
var express = require('express');
var mongoose = require('mongoose');
const bodyParser = require('body-parser');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function(){
// CONNECTED TO MONGODB SERVER
console.log("Connected to mongod server");
});
mongoose.connect("mongodb+srv://testing1:7894#cluster0.9hxjc.mongodb.net/data?
retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology:
true });
var app = express();
var test = require('./route/index');
var test2 = require('./route/signup');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.set('views',__dirname+'/views'); // ==
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
app.use('/',test);
app.use('/signup.ejs',test2);
app.listen(3000,function(){
console.log('hello world');
});
Hello, I am studying using mogoose and node.js. I ran mongoose find() but the result was only []. I don't know why this is so, I would appreciate it if you let me know. And if it is findOne(), how should I write it? I tried writing it once, but it turned out to be null.
Through chatting in comments we found the issue. The model is called user:
module.exports = mongoose.model('user',userSchema);
Which mongoose will connect to a collection named users (plural) in MongoDB. That collection was indeed empty. There was only content in a collection named user.
I am learning about Mongoose. I am working along this tutorial and running into a stumbling block with adding entries to my database, run through Heroku MongoDB. I am able to add to the existing collection "test1" when I load the app 'trywithmongodb' but I in my Heroku mLab console I do not see anything added to any collections when I access the page "trywithmongoose". Help? Here is the relevant code for in index.js:
var express = require('express');
var mongoose = require("mongoose");
var mongo = require('mongodb').MongoClient;
app.get("/trywithmongodb", function(request,response){
response.send("Looking at the /trywithmongodb page");
var configDB = require('./config/database.js');
//add to the database
mongo.connect(configDB.url , function(err, db) {
var shorturl = db.collection("test1");
var date = new Date();
var newsitejson={original_url: "accessed at", site_number: date.getHours()+":"+date.getMinutes()}
shorturl.insert(newsitejson)
db.close()
})
});
app.get('/trywithmongoose', function (request, response) {
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
// grab the user model
var User = require('./app/models/user');
// create a new user
var newUser = User({
name: 'Peter ',
username: 'peter45',
password: 'willbehashed',
admin: true
});
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
response.send("You are looking at /trywithmongoose");
});
And here's the full file user.js for the schema:
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
Following step by step a simple installation of resourcejs as documented in this MEAN App repo, I get the following message, when I access the URL http://localhost:3000/movie/584c6f00cf996a9956784807:
{"status":500,"message":"Cast to ObjectId failed for value \"584dd2842a056e4a648751b5\" at path \"_id\" for model \"movie\"","errors":{}}
POST requests work too, but PUT and DELETE do not.
index.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var methodOverride = require('method-override');
var _ = require('lodash');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
// CORS Support
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
mongoose.connect('mongodb://localhost/meanapp');
mongoose.connection.once('open', function() {
// Load the models.
app.models = require('./models/index');
var routes = require('./routes');
var numberOfRoutes = 1;
_.each(routes, function(controller, route) {
app.use(route, controller(app, route));
});
app.listen(3000);
});
MovieController.js
var Resource = require('resourcejs');
module.exports = function(app, route) {
// Setup the controller for REST;
Resource(app, '', route, app.models.movie).rest();
// Return middleware.
return function(req, res, next) {
next();
};
};
The Movie model looks just like this, and is being served this way.
My point of interest is that ResourceJS has this following code, which seems to not be able to parse correctly an ID into a MongoDB ObjectID:
/**
* Register the GET method for this resource.
*/
get: function(options) {
(…)
var search = {'_id': req.params[this.name + 'Id']};
(…)
}
What could possibly be messing this up?
Stats
Windows 10 — 64-bit OS, x64-based processor
MongoDB v3.2.7, 64-bit
NodeJS v4.4.7
Mongoose v4.7.6
Because mongoose wants ObjectId but You're passing string as _id, so You should typecast it.
Try this:
var
mongoose = require('mongoose');
ObjectId = mongoose.Schema.Types.ObjectId;
/**
* Register the GET method for this resource.
*/
get: function(options) {
(…)
var param = req.param[this.name + 'Id'];
var search = {'_id': new ObjectId(param)};
(…)
}
If You need universal solution that works with any version of Mongoose and Mongo just define _id field as string and use uuid.v4 to generate unique values:
var uuid = require('uuid');
var mongoose = require('mongoose');
// Create the MovieSchema.
var MovieSchema = new mongoose.Schema({
_id: {
type: String,
index: { unique: true },
default: uuid.v4
},
title: {
type: String,
required: true
},
url: {
type: String,
required: true
}
});
// Export the model.
module.exports = mongoose.model('movie', MovieSchema);
So in this case Your ResourceJS will stay as before and work properly:
get: function(options) {
(…)
var search = {'_id': req.param[this.name + 'Id']};
(…)
}
P.S. don't forget to install uuid package:
npm i --save uuid
Given the following schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var favoriteSchema = new Schema({
dishes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true
});
var Favorites = mongoose.model('Favorite', favoriteSchema);
module.exports = Favorites;
and the following router
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.create(req.body,function(err,fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
module.exports = favoritesRouter;
Every time i do the post requires from postman, I`m attaching the dish ID to the body of the request.
{
"_id": "577a996155d73cf02b0d516f"
}
I could not come up with a solution to insert this ID into the array, instead of re-creating the whole object with only 1 id inside the array. Am i making something wrong, or something else has to be done in order to do the logic i want?
You're going to want to query the database to find the previously saved object, append to the array, mark as modified, then save. It will look something like this:
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.findById(someID, function(err, fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.markModified('dishes')
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
You'll need to figure out how you're getting the ID in there. You could use a dynamic endpoint:
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/:id')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
var someID = req.params.id
})
Or you could do a search for who posted it (.find({postedBy: req.decoded._doc._id},... instead of .findById(someID,...), or something else
The issue that it doesnt let me use the genre schema
i have 2 schemas user and genre
user schema works fine but the genre schema is undefind
user.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Genre = require('../Models/genre');
// create a schema
var userSchema = new Schema({
name: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
age: String,
gender: String,
genres: [Genre.genreSchema]
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
genre.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var genreSchema = new Schema({
name: { type: String, required: true, unique: true },
age: String,
gender: String
});
// the schema is useless so far
// we need to create a model using it
var Genre = mongoose.model('Genre', genreSchema);
// make this available to our genres in our Node applications
module.exports = Genre;
genre controller - router --- same as user router controller
var express = require('express');
var bodyParser = require('body-parser');
var Genre = require('../Models/genre');
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/genres')
// create a genre
.post(function(req, res) {
console.log(Genre);
**//here is the error when trying to post new genre**
var Genre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
Genre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});
})
// get all the genres
.get(function(req, res) {
Genre.find(function(err, genres) {
if (err)
res.send(err);
res.json(genres);
});
});
module.exports = router;
server.js - the app js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userRouter = require('./Controllers/user');
var genreRouter = require('./Controllers/genre');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017'); // connect to our datababase
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', userRouter);
app.use('/api', genreRouter);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('see whats happening on port ' + port);
why the model is undefind only when i post new genre? and for user it works fine?
is it the way to do schema whithin schema? or there is a better way?
i have try to use only the genre model with out the user and it still same error
i hope i am clear enough
thanks for the helpers
You shouldn't be using the same name for the schema and for the new Genre.
try changing it to
var newGenre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
newGre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});