i have a pre-existing collection (which is on mongodb atlas), and i've connected it and cerate Modules and Schemas, and i can console log it , so far so good, but when i export the module to index.js i can't console log the data it say Model.find is not a fucntion.
PS.
i'm new to this
My code:
var mongoose = require('mongoose');
var uri = 'mongodb+srv://USER:PASSWORD#wt-cluster-xd7ou.mongodb.net/test?
retryWrites=true'
mongoose.connect(uri, {dbName: 'dbName'});
mongoose.Promise = global.Promise;
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {
var menuSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
category: String,
food_name: String,
food_desc: String,
food_price: String
});
var Menu = mongoose.model('Menu', menuSchema, 'menu');
Menu.find(function(err, menus){
if(err) return console.err(err);
console.log(menus);
})
module.exports = Menu;
});
this console log my data correctly
index.js
var express = require('express');
var router = express.Router();
var Menu = require('../models/menu')
var assert = require('assert')
/* GET home page. */
router.get('/', function(req, res, next) {
Menu.find({}, function (err,menus) {
assert.equal(err,null);
res.send(menus);
});
});
module.exports = router;
here is where i'm trying to send the data to the HTML
It appears you are defining and exporting your model inside the connection.on() function. Try defining those in a separate file and see if that helps.
Create your model in a separate file.
var mongoose = require('mongoose');
let connection = require('connnection.js')
var menuSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
category: String,
food_name: String,
food_desc: String,
food_price: String
});
var Menu = mongoose.model('Menu', menuSchema, 'menu');
Menu.find(function(err, menus){
if(err) return console.err(err);
console.log(menus);
})
module.exports = Menu;
Change your db connection to
var mongoose = require('mongoose');
var uri = 'mongodb+srv://USER:PASSWORD#wt-cluster-xd7ou.mongodb.net/test?
retryWrites=true'
mongoose.connect(uri, {dbName: 'dbName'});
mongoose.Promise = global.Promise;
var connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function(){
console.log('Database ready.')
})
module.exports = connection
Save this as connection.js for require to work.
Test the route again.
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.
How do I set my database and collection using mongoose ? I am trying to connect to a mongodb atlas database using mongoose. My database is called "test_db" and collection name is "users" where would I specify that information ?
This is my shema (data.js):
// /backend/data.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// this will be our data base's data structure
const DataSchema = new Schema(
{
_id: Number,
name: String,
password: String
}
);
// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("users", DataSchema);
and this is server.js:
const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
// this is our MongoDB database
const dbRoute = 'mongodb+srv://<user>:<password>#cluster0-bmihj.mongodb.net/test?retryWrites=true&w=majority';
;
// connects our back end code with the database
const conn = mongoose.connect(dbRoute, { useNewUrlParser: true });
//let db = mongoose.connection;
const db = conn.db('test_db');
var MyModel = mongoose.model('Test', new Schema({ name: String }));
db.once('open', () => console.log('connected to the database'));
// checks if connection with the database is successful
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// this is our get method
// this method fetches all available data in our database
router.get('/getData', (req, res) => {
Data.find((err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
Through this line, you are connected to MongoDB:
const conn = mongoose.connect(dbRoute, { useNewUrlParser: true })
Consider:
dbRoute = mongodb://DB-username:DBpassword#ds245901.mlab.com:44422/Database-Name";
Here is your data information
DB-username = Your database user name
DBpassword = Your database password
Database-Name = Your database name (which database you want to use)
Therefore, no need to connect to your desired database like this:
const db = conn.db('test_db');
I have my file to add data to mongo via mongoose :
var mongoose = require('mongoose');
var mongoDB = 'mongodb://myuser:mypass#ds145293.mlab.com:45293/employees';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open',function(){
console.log('connected')
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
});
})
mongoose.connection.close()
Copied almost verbatim from mongoose site.I am able to connect to the database but i dont get the 2nd console log.I have a db but no collections.Is this the problem?
Replace mongoose.Schema with new Schema and also I don't think this mongoose.Promise = global.Promise is required.
It cant complete the save before you close the database. There are many options to wait for the save. I like async/await.
edit: sorry that was too quick. Updated example.
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
async function run() {
await mongoose.connect(mongoDB);
console.log('connected')
var kittySchema = new mongoose.Schema({ name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
await fluffy.save();
console.log('saved');
mongoose.connection.close();
}
run();
Or you can just move the close to after you have saved:
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open', function () {
console.log('connected')
var kittySchema = new mongoose.Schema({name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
mongoose.connection.close();
});
})
I am new to nodejs and express.When i try to do get request from the mongoose database in mlab.com i get an empty response.
my serve code is (app.js),
var express = require('express');
var mongoose = require('mongoose');
var app = express();
var db =mongoose.connect('mongodb://test:test#ds155695.mlab.com:55695/app');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected');
});
var user = require('./model/userModel');
var routers = express.Router();
routers.route('/getUSers').get(function(req,res){
user.find(function(err,users){
if(err) {
console.log(err);
} else {
res.json(users);
}
});
});
app.use('/api',routers);
app.listen(8000,function() {
console.log('server working');
});
My model is userModel.js
var mongoose = require('mongoose');
var app = mongoose.Schema({
firstName : String,
lastName : String
});
module.exports = mongoose.model('users',app);
can anyone help me where am i going wrong !
I have a strange issue with MongoDB-mongoose, which does not respond to REST API
mongoose version - 4.11.3
Mongo DB shell version 3.4.6
Everything is local on my computer
Connection to Mongo DB is the following:
server.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});
...
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
The log "Connected correctly to db" is printed.
Schema (tasks.js)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskSchema = new Schema({
name: String
});
var Task = mongoose.model('Task', taskSchema);
module.exports = Task;
And finally taskRouter.js
var express = require('express');
var bodyParser = require('body-parser');
var Task = require('../models/tasks');
var taskRouter = express.Router();
taskRouter.use(bodyParser.json());
taskRouter.route('/')
.get(function (req, res, next) {
Task.find({}, function (err, task) {
console.log("result"+task)
if (err) throw err;
res.json(task);
});
})
.post(function (req, res, next) {
var task = new Tasks();
console.log ('the name is '+req.body.name);
task.name = req.body.name;
task.save(function(err){
console.log ("arrived there");
if (err)
res.send(err);
res.json({message: "Task created"});
});
})
As you see, everything is by the book .
But I never get any logs from task.save and Task.find
My 'morgan' logger shows just the following logs:
GET /api/tasks - - ms - -
POST /api/tasks - - ms - -
Postman is stuck on "Loading", until receives a timeout: Could not get any response.
All simple operation on the tasks collection in Mongo DB shell are performed without any problem.
What happens with mongoose?
Thanks in advance.
Try to create a separate file config.js with the following code :
module.exports = {
'database': 'mongodb://localhost:27017/yourdatabasename'
}
server.js:
...
var config = require('./config'); // get our config file
...
var mongoose = require('mongoose');
...
mongoose.connect(config.database, { useMongoClient: true });
mongoose.connection.on('open', function(err, doc){
console.log("connection established");
var app = express();
var tasks = require('./server/routes/taskRouter');
app.use('/api/tasks',tasks);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected correctly to db");
});