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();
});
})
Related
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.
On local, I installed NodeJS 9.2 and MongoDB 3.4
I using MongoDB Native Node Driver 3.0.4
My code with database
const mongo = require('mongodb').MongoClient;
const mongoose = require('mongoose');
mongo.connect('mongodb://localhost:27017/my_database', function(err, client){
console.log(err);
if (!err){
var database = client.db('my_database');
database.collection('users').find({}).toArray(function(err, docs){
console.log(docs);
});
}
});
Result null for error and array users in collection
So, on server centos 7 installed nodejs 8.2, Result null for error and empty array for docs
How does it work?
Connection
const mongoose = require('mongoose');
const URL = "mongodb://user:pass#mongo:27017/database?authSource=admin";
mongoose.connect(URL, {"server":{"auto_reconnect":true}});
var db = mongoose.connection;
db.on('error', function(err) {
console.error('Error in MongoDB connection: ' + err);
});
db.on('connected', function() {
console.log('Connected to MongoDB');
});
Model
You create a schema that represents a collection in your db
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MyModel = Schema({
foo: String
}, { collection: 'mycollection' });
module.exports = mongoose.model('MyModel', MyModelSchema);
Controller
You use this schema to execute requests to that collection
const MyModel = require('../models/mymodel');
function myFunction(req, res) {
MyModel.find({}).exec(function(err, result){
if(!result) return res.status(404).send();
var array = [];
result.map(function(data){
array.push(data.foo);
});
res.status(200).send({"mydata": array});
});
}
module.exports = {
myFunction
};
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");
});
I am new to node.js . I am trying to create one connection in server.js and use it in addAcction.js but got error while running "Software is not
a constructor", Please help me this?
//Server .js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/MSDN');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function callback() {
console.log("Connection with database succeeded.");
});
module.exports = db;
var SoftwareSchema = new mongoose.Schema({
SoftwareID: Number,
SoftwareName: String,
});
module.exports = mongoose.model('Software', SoftwareSchema);
//addAction.js
var Software = require('./Server').Software;
var Software1 = new Software({
SoftwareID : 1,
SoftwareName : "MNG123",
});
Software1.save(function(err){
if ( err ) throw err;
console.log("Software Saved Successfully");
});