I'm having trouble figuring out how to save a json object from a third party api to my personal localhost mongodb. I believe I'm supposed to create another method within the api controller but am not sure what kind of method should be used any help would be great thanks!
Here is my code sorry if this is a dumb question.
//server.js
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var mongoose = require('mongoose');
var Router = require('./routes');
var morgan = require('morgan');
var port = process.env.PORT || 3000;
var app = express();
//database connect
mongoose.connect('mongodb://localhost/Emagispace')
app.use(
express.static('views'),
bodyParser.json(),
bodyParser.urlencoded({extended : true}),
morgan('dev')
);
Router(app);
app.listen(port, ()=>{
console.log(`Server running on ${port}`);
//Routes
var API = require('./controllers/api');
module.exports = (app)=>{
app.get('/', (req, res)=>{
res.sendFile('index.html', {root : './views'});
});
app.get('/api/emagispace', API.product)
}
//API controller
var request = require('request-promise');
var baseURI = 'example';
module.exports = {
product : (req, res)=>{
request({
method : 'GET',
url : `${baseURI}/api/emagispace/${req.query.products}`
})
.then((resp)=>{
console.log('Product list : ', resp);
res.send(resp).save();
})
}
}
In order use mongoose for saving the documents you'll need to specify the Schema first.
//product-model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: String,
price: String,
//And all other data you need
});
var Product = mongoose.model('Product', ProductSchema);
Also you can do validation and much else. Please see the docs.
Then you can use .insertMany to save them in one shot or iterrate over your documents:
var Product = require('../models/product-model.js');
...
.then((resp)=>{
//I assume that resp is an array of products here
console.log('Product list : ', resp);
//Go over your product list and save them
for (var product of resp) {
var p = new Product(product);
p.save();
}
//OR
Product.insertMany(resp);
res.send(resp);
})
After this you'll have products collection in your local db.
Also you can warp these calls into a method if you want.
Related
I have been doing a project in URL shortening and i am getting an undefined as a result to get request.
Also i get a blank page too as result,but according to my knowledge everything is ok,i can't figure out what is the mistake
Here's my code(please check the app.get section)
'use strict';
var bodyParser = require('body-parser')
var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var http = require("http");
var cors = require('cors');
const dns = require('dns');
var app = express();
// Basic Configuration
var port = process.env.PORT || 3000;
/** this project needs a db !! **/
// mongoose.connect(process.env.DB_URI);
app.use(cors());
/** this project needs to parse POST bodies **/
// you should mount the body-parser here
app.use('/public', express.static(process.cwd() + '/public'));
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/views/index.html');
});
// your first API endpoint...
app.get("/api/hello", function (req, res) {
res.json({greeting: 'hello API'});
});
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
var saveSchema = new mongoose.Schema({
name: String,
url: Number,
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
/** 3) Create and Save a Person */
var SaveData = mongoose.model('Save', saveSchema);
//**Here's the start of my problem,i think**
app.get("/api/shorturl/:id1",function(req,res){
SaveData.find({url:1},function(err,data){ console.log(data.name)//**i am getting undefined for this in console**
res.json(data.name);})
});
app.post("/api/shorturl/new",(req,res)=>{
var body=req.body.url;
dns.lookup(body,(err,data)=>{
var new2= new SaveData({name:body,url:1});
new2.save((err,data)=>{res.json(new2);});
})
});
app.listen(port, function () {
console.log('Node.js listening ...');
});
I checked my DB whether the schema data is inputted or not, it is getting inside DB, so retrieval makes the problem I think.
mongoose.model.prototype.find returns an array of objects found. If you type Array.prototype.name in a console somewhere, you'll get undefined. Instead, use mongoose.model.prototype.findOne.
Your enviorment variables are working? I notice you're not using dotenv module or something like that to configure your process.env.
Im reffering this video tutorial from this link "https://app.pluralsight.com/player?course=node-js-express-rest-web-services&author=jonathan-mills&name=node-js-express-rest-web-services-m6&clip=2&mode=live"....Here im returning the student in the json format...But dont know how to create it...So im getting an empty one...Is there any way to create that in the mongoose...Any1 please check my code and say
app.js
var express = require('express'),
mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/studentAPI');
var studentinfo = require('./models/studentModel');
var app = express();
var PORT = process.env.PORT || 3000;
var tutorRouter =express.Router();
tutorRouter.route('/student')
.get(function(req,res){
studentinfo.find(function(err,student){
if(err)
res.status(500).send(err);
else
res.json(student);
});
});
app.use('/api',tutorRouter)
app.get('/',function(req,res){
res.send('Welcome to my API')
});
app.listen(PORT,function(){
console.log('Running on port: ' + PORT);
});
studentModel.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema();
var studentModel = new mongoose.Schema({
name:{
type: String
},
parentname:{
type: String
}
});
module.exports = mongoose.model('studentinfo',studentModel);
I have this very simple code that stores superhero name and power to database.
All connections work normally. When i ran mongod i used --dbpath C:/nodeprojects/sankarit/data. I have tried change the path like 50 times with different paths.
So my code sends nimi and supervoima (name, superpower) from client side and it tries to add them to database but literally nothing happens in db. When i write console.log("yay it works") on save function, it says that its working. And if i console log superhero it seems to work normally.
Here is client side:
$http.post("api/juttu", {nimi: "besthero", supervoima: "whiskey"}).success(function(response){
console.log(response.data);
}).error(function(){
console.log("Error")
})
Here is my server.js:
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.set('debug', true);
// SANKARI SCHEMA
var Sankari = require('./app/models/sankarit');
// CONTROLLERIT
var testCtrl = require('./server/testCtrl');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use('/public', express.static(__dirname + '/public'));
// DB conn
// I have tried with /test, /heros, /sankariKanta, /sankarit
mongoose.connect('mongodb://127.0.0.1:27017/test');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
//PORTTI
var port = process.env.PORT || 8080;
// ROUTER
var router = express.Router();
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
app.post("/api/juttu", testCtrl.juttu);
app.listen(port);
Here is the testCtrl:
var Sankari = require("../app/models/sankarit");
module.exports.juttu = function (req, res){
// Tried also var uusiSankari = new Sankari(req.body);
var uusiSankari = new Sankari();
uusiSankari.nimi = req.body.nimi;
uusiSankari.supervoima = req.body.supervoima;
uusiSankari.save(function(err){
if(err){
console.log(err);
} else{
// This is always showing up
console.log("This is working!");
}
});
};
Also when i try console.log(req.body); It is working correctly.
Here is schema(sankarit.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = ({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);
When i run the program, the mongoose debug thing says:
Mongoose: sankaris.insert({ __v: 0, _id: ObjectId("57ff0a649dbf169c15000001"), nimi: 'besthero', s
upervoima: 'whiskey' }) {}
So when i debug and console log everything the program does it seems to work like dream. I have made these MEAN stack tutorials like 5-10 and everytime database worked normally. This is first time i'm trying to make whole code by myself. I tried solve this whole night but i didn't get absolutely anywhere.
You forgot to use the Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = Schema({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);
I trying to get data from mLab.
In function /getAll I am trying to get all the JSONs I entered in a collection.
I understood that to get all of the details I need to use the function find.
When I run it (node app.js) - I can see it waiting but nothing happens and I don't get anything on localhost:3000/getAll (it's not loading)
here is app.js
var express = require('express');
var app = express();
var stud = require('./grades');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://<myuser>:<mypass>#<dataaddress>');
var port = process.env.PORT || 3000;
mongoose.connection.once('open', function(){
stud(app);
mongoose.disconnect();
});
app.listen(port);
and this is gadres.js
var express = require('express');
var fs = require('fs');
var app = express();
var util = require('util');
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var studSchema = new schema({
id : {type:Number, unique:true, required:true},
name : {type:String, required:true},
grade : Number,
course : {type:String},
year : Number
},{collection: 'details'});
var stud = mongoose.model('stud', studSchema);
module.exports = function (app) {
app.get('/getAll', function(req, res) { // if url in path is getAll
stud.find({}, function(err, user){
if(err) throw err;
console.log(user);
});
})
});
I am very new to node JS and mongo.
I am working on a personal website that stores a user's information in my database.
For simplicity, let's say I have the following form in jade...
form(class="inputs", action="/login", method="post")
input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email")
I already set up a database, and I was able to connect to it using the following javascript...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function() {
// Create your schemas and models here.
});
I want to store the input from email for every user that registers using the form above.
I am guessing I would first have to create a schema, which would probably look like this, but I'm not sure...
var Schema = mongoose.Schema;
var userSchema = new Schema({
email: String
});
//I think I have to create a model too?
And to get POST data I think I would need some code that looks like this...
app.post('/login', function(request, response){
//I am not sure what to put inside
});
My question is, can someone show me how to implement all these together so that every time a user registers with their email, it is saved in the database. It is very hard to research this, and have tried and failed many times.
EDIT
Here is my index.js file...
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'QChat' });
});
module.exports = router;
Also, here is another file in my routes directory called users.js, I'm not sure what its purpose is...
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
Here are some sample codes, hope it could help you.
var userSchema = new Schema({
email: String
});
var User = mongoose.model('User', userSchema);
app.post('/login', function(request, response){
var u = new User({
email: request.body.name
});
u.save(function(err) {
if (err)
throw err;
else
console.log('save user successfully...');
});
});
Also to parse the post url correctly, express could be used here, sample codes as below.
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
user.model.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, Q = require('q')
;
var UserSchema = mongoose.Schema({
email: String,
})
UserSchema.methods.Save = function() {
return Q.ninvoke(this, 'save');
}
var User = mongoose.model('User', UserSchema);
user.controller.js
var mongoose = require('mongoose')
, User = mongoose.model('User')
;
app.post('/create', function(request, response){
var user = new User();
user.email = request.body.email;
return user.Save().then(function(users) {
// some code if save succeed
}, function(err){
// some code if save failed
});
});