I need to use a different database for users.
Information about database name is stored in the user profile.
How can i make a database connection using a profile information?
In my model a use this code.
var mongoose = require('mongoose');
var db2 = mongoose.createConnection('mongodb://localhost/testdb' );
var Order = db2.model('Order');
exports.show = function(req, res, next){
Order.find(function(err, order){
if(err) return next(err);
res.render('order/index',{
orders: orders,
});
});
}
Related
I'm a total beginner at this and am using a tutorial to learn the basics of the MEAN stack. I am trying to return the documnents in my database to a web page but am instead receiving an empty array.
I have created a cluster on Mongodb Atlas called mytasklist. Inside here I created a database called mytasklistdb. Inside this I have a table (object) called mytasklistdb.mytasklisttutorial. My understanding of this is limited and so maybe I'm making a huge error somewhere here. I have experience of SQL but not Mongo and so the whole 'clusters' and 'collections' thing is new to me.
Anyway my code is as follows. I took the string for the database connection from the Mongo connection tab.
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb+srv://myusername:mypassword#mytasklist-qx0ka.mongodb.net/test?retryWrites=true&w=majority', ['mytasklisttutorial']);
router.get('/tasks', function(req, res, next){
db.mytasklistdb.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
My database objects look like this:
_id:5db5f1f31c9d440000c3e7fe
title:"Walk the dog" - this is a string
isDone:false - this is boolean
I'm just getting an empty array but in the tutorial the guy is getting these 'documents'. What am I doing wrong?
EDIT: I realised that the 'tasks' part of the tutorial example was relating to a database called 'tasks'. Mine is called 'mytasklistdb'. I therefore changed this. I also added a parameter with the name of my collection to the line passed in to mongojs.
I have changed my code above to reflect this
The solution was to replace 'task' and 'test' with the name of my db. As follows:
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb+srv://James:Noentry1#mytasklist-qx0ka.mongodb.net/mytasklistdb?retryWrites=true&w=majority', ['mytasklisttutorial']);
router.get('/tasks', function(req, res, next){
db.mytasklisttutorial.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
My guess is that you are not passing your query, just the callback in the find() method, probably you need to do something like this:
db.tasks.find({},function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
I am trying to insert a sub document into all existing documents in a collection in db,in nodejs using express framework.Following is the code snippet:
updatedoc: function(update,options,cb)
{
return this.update({},update,options).exec(cb);
}
where parameters update and options are as follows :
const update = { $push: { "defaultads": content }};
const options = { multi: true};
It seems to run and gives the following output on the console :
{ n: 1, nmodified: 1, ok: 1 }
but no push takes place at all ,in any of the documents of the database.
I have checked :
1) whether i am pushing in the right db.
2) whether correct values are being passed
However I am not able to find where I am going wrong.
I am new to nodejs and would really appreciate guidance in solving this problem.
Thanks in advance.
I am giving a simple code with full fledged requirement of yours. First create a config.js using this file you will be connected to mongodb.Here is the code
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/product'
}
Next create a models folder . Keep this schema in this models folder . I named it as product.js. Here is the code
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imagepath:{
type:String
}
});
var nameSchema = new mongoose.Schema({
productName:{type: String},
productPrice:{type: Number},
imagePaths:[imageSchema]
});
module.exports = mongoose.model("product", nameSchema);
Next create a routes folder and keep this routes code in this folder I named it as route.js. Here is the code
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Product = require('../models/product');
var app = express();
var Router = express.Router();
Router.use(bodyParser.json());
Router.get('/product',function(req,res){
Product.find({}, function (err, product) {
if (err) throw err;
res.json(product);
});
})
Router.post('/productData',function(req, res, next){
Product.create(req.body, function (err, product) {
if (err) throw err;
console.log('Product Data created!');
var id = product._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the product data with id: ' + id);
});
})
Router.post('/subdocument',function (req, res, next) {
Product.find({},function (err, result) {
if (err) throw err;
for(var i=0;i<result.length;i++){
result[i].imagePaths.push(req.body);
result[i].save(function (err, ans) {
if (err) throw err;
console.log('SubDocument created!');
});
}
res.send("Successfully added");
});
})
module.exports = Router;
Next server code I named it as app.js. Here is the code
var express = require('express');
var bodyParser = require('body-parser');
var Product = require('./models/product');
var mongoose = require('mongoose');
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var app = express();
var route=require('./routes/route');
app.use('/route',route);
app.listen(3000,function(){
console.log("Server listening on 3000");
});
Run the server as node app.js.
API's
Use GET method http://localhost:3000/route/product .This is for getting all the product information.
Use POST method http://localhost:3000/route/productData .This for creating document. Post data in json format through request body like
{
"productName" : "sweets",
"productPrice" : "33"
}
You will see the response like this.
First post some documents i.e., post 2 or 3 documents and then you can see the documents with get API as I mentioned above. Then you will see all the documents contains empty sub document. You will see the response like this
And now add the sub document to all using the below api.
Use POST method http://localhost:3000/route/subdocument . Using this you can add a sub document to all the documents like this you need to add sub document
{
"imagepath" : "desktop"
}
You can see the response like this
After this again when you run the get API you can see all the sub documents are added to all documents.
Hope this helps.
I am trying to load data from my database named users which contains 2 users in the collection named userlist. Each entry has a name and age.
The code below resides in my app.js.
//set database connection
mongoose.connect('mongodb://localhost:27017/users');
mongoose.connection.on('error',function(){
console.log('MongoDB Connection Error. Please make sure that MongoDB is running');
process.exit(1);
});
mongoose.connection.once('open',function(callback){
console.log('Connected to Database');
});
var userSchema = new mongoose.Schema({
name:{type:String,uppercase:true},
age:Number
});
var userModel = mongoose.model('userModel',userSchema);
app.get('/users', function(req, res, next) {
userModel.find({},function(err,userModel){
res.send(userModel);
//Have tried res.send(userlist) also
})
});
This returns an empty set [] on localhost:3000/users. However i do have two entries in my database.
var userSchema = new mongoose.Schema({
name:{type:String,uppercase:true},
age:Number
},{collection:'userlist'});
This is what helped me.
I have created nodejs(expressjs) application with mongodb on Openshift.
and I have pushed my database (mehendiDB) on the mongodb server which I can see on the server by using rockmongo cartridge as follows
admin(2)
api(3)
local(1)
mehendiDB(5)
Comments(10)
Likes(10)
Posts(8)
Users(9)
system.indexes(4)
Though I can see the data uploaded onto server but when I retrive it with the following code from my users.js I do not get anything but an empty array. Code I ave written in users.js is as follows
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
router.dbServer = new mongodb.Server(process.env.OPENSHIFT_MONGODB_DB_HOST,parseInt(process.env.OPENSHIFT_MONGODB_DB_PORT));
router.db = new mongodb.Db(process.env.OPENSHIFT_APP_NAME, router.dbServer, {auto_reconnect: true});
router.dbUser = process.env.OPENSHIFT_MONGODB_DB_USERNAME;
router.dbPass = process.env.OPENSHIFT_MONGODB_DB_PASSWORD;
router.db.open(function(err, db){
if(err){ throw err };
router.db.authenticate(router.dbUser, router.dbPass, {authdb: "admin"}, function(err, res){
if(err){ throw err };
});
});
router.get('/', function (req, res){
router.db.collection('Users').find().toArray(function(err, names) {
console.log("Printing output : " + names);
res.header("Content-Type:","application/json");
res.end(JSON.stringify(names));
});
});
module.exports = router;
PS : I am not getting any errors in the log console(nodejs.log) when I checked it. and showing 'Printing output'
Thanks in advance.
Have you verified that the database name that you uploaded your data to is the same as the process.env.OPENSHIFT_APP_NAME that you are using within your application?
I am trying to create a login system where an admin can log in and look at data that is not available to the public. Right now I'm just trying to find my admin instance in my database. I have two node files: app.js and account_manager.js
app.js
//creates node app
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var AM = require('./account_manager');
//stuff...
/***************************************
LOGIN
***************************************/
app.post('/login', function(req, res){
AM.manualLogin(req.param('username'), req.param('password'), function(e, o){
if (!o){
res.send(e, 400);
} else{
req.session.user = o;
res.send(o, 200);
}
});
});
account_manger.js is required in app.js and is stored in AM
account_manager.js:
var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');
var admin_db = mongoose.connection;
admin_db.on('error', console.error.bind(console, 'connection error: '));
//connection open?
admin_db.once('open', function callback(){
console.log("User Database connection open!\n");
});
var User_Schema = new mongoose.Schema({username: String, password: String});
var Admin = mongoose.model('Admin', User_Schema);
exports.manualLogin = function(user, pass, callback)
{
admin_db.find({username: user},function(err,docs){ //error is here
if(docs){
var x = 0;
var flag = false;
while(docs[x]){ //goes through all the admins
if (docs[x].param("username") == user){ //if it's a match
callback(null, docs);
flag = true;
break;
}
x+=1;
}
if (flag == false){
callback('invalid-password/username');
}
}
});
}
I get a TypeError that says:
Object #<NativeConnection> has no method 'find'
what's my problem?
I'm still quite new to node.js myself, but I'll try and answer anyway.
It looks like you've properly built your connection to mongodb through mongoose, but you have not created a schema. While mongodb doesn't have schemas, mongoose does.
What you'll need to do is create a schema (UserSchema) that matches the construction of a user document in your users collection, then create an instance of that schema (User) which is now your model, then call .find on that model.
The Mongoose Quick Start guide goes through this process:
http://mongoosejs.com/docs/index.html
EDIT after update:
You are currently calling admin_db.find. This does not exist. This is the error you are getting.
You need to change that to Admin.find. You also need to understand what the difference is.
EDIT once more:
You're not properly using the admin_db.once callback.
I suggest you go back and reread the Mongoose Quick Start guide I linked. It's quite short and goes through all of this.
I see you're rolling your own system here, but I thought I'd share a link to Drywall in case you could gain some inspiration or knowledge from it.
Drywall - A website and user system for Node.js: http://jedireza.github.io/drywall/
I hope this is helpful. Feel free to open issues in GitHub if you run into any road blocks.