MongoDB data return [] - mongodb

I'm making a project for my college assignment, but I'm having a trouble while i'm trying to get a data from database called 'project' in 'sitelist' collection from MongoDB.
But for some reason the data i got is only an empty array [ ].
I'm new to MongoDB so i want to know where did i do wrong.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const SLDBModel = require('./sldb_schema');
require('./db');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: true }))
app.use(function (req, res, next)
{
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers','content-type, x-access-token');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get('/api/getList', function (req, res){
SLDBModel.find({},function(err, data){
if(err){
console.log('//app.get// getList error!...');
res.send(err);
}
else{
console.log(data);
res.send(data.map(v => v.toJSON()));
}
});
});
module.exports = app;
app.listen(3000, ()=>{
console.log("SERVER IS ONLINE! ON PORT 3000");
})
sldb_schema.js
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SLSchema = new Schema({
S_NAME: {type: String, required: true},
S_ADD: {type: String, required: true},
S_STATUS: {type: String, required: true}
}
);
const SLDBSchema = new Schema({
list: [SLSchema]
}
);
const SLDBModel = mongoose.model('sitelist', SLDBSchema);
module.exports = SLDBModel;
db.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/project', {useUnifiedTopology: true, useNewUrlParser: true });
mongoose.connection.on('connected', function () {
console.log('MONGOOSE default connection open');
});
mongoose.connection.on('error', function (err) {
console.log('MONGOOSE default connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('MONGOOSE default connection disconnected');
});
process.on('SIGINT', function () {
mongoose.connection.close(function ()
{
console.log('MONGOOSE default connection disconected through app termination');
process.exit(0);
});
});
Data in database called 'project' in collection 'sitelist'
{
"_id" : ObjectId("5ec4672e44f01dcae82c3dde"),
"error" : "0",
"num_rows" : 3,
"list" : [
{
"S_NAME" : "SBOBETH",
"S_ADD" : "sbobeth.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "GTRCASINO",
"S_ADD" : "gtrcasino.com",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "SBOBETH",
"S_ADD" : "sbobeth.com",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "GTRBETCLUB",
"S_ADD" : "gtrbetclub.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "77UP",
"S_ADD" : "77up.bet.com",
"S_STATUS" : "UP"
},
{
"S_NAME" : "DATABET88",
"S_ADD" : "databet88.net",
"S_STATUS" : "DOWN"
},
{
"S_NAME" : "FAFA855",
"S_ADD" : "fafa855.com",
"S_STATUS" : "UP"
}
]
}

Because your collection's name is not pluralize. Please check answer in below link.
MongoDB and Mongoose: Cannot retrieve data

Related

Problem to send data on Express.js / MongoDB

i get error about Body-Parser when i post data with Postman on localhost:3000/send-data
, i thought it can get fixed with express.json() but it didn't, also what is the simplest way to post data to mongoDB with React-native?
here are my codes:
app.js :
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
require("./ads")
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
const Ads = mongoose.model("ads")
const mongoURI = *
mongoose.connect(mongoURI, {
useNewUrlParser : true,
useUnifiedTopology: true
})
mongoose.connection.on("connected",() => {
console.log("connected to server")
})
mongoose.connection.on("error",(err) => {
console.log("error",error)
})
app.post('/send-data',(req,res) => {
const ads = new Ads({
name : req.body.name,
title : req.body.title,
title2 : req.body.title2,
})
ads.save()
.then(data => {
console.log(data)
res.send("seccsudss")
}).catch(err => {
console.log(err)
})
})
app.get('/',(req,res) => {
res.send("welcome to nodejs")
})
app.listen(3000,() => {
console.log('listening on 3000')
})
and error i get is :
SyntaxError: Unexpected token } in JSON at position 185
at JSON.parse (<anonymous>)
at parse (/home/kian/project/project/project/node_modules/body-parser/lib/types/json.js:89:19)
at /home/kian/project/project/project/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/home/kian/project/project/project/node_modules/raw-body/index.js:224:16)
at done (/home/kian/project/project/project/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/home/kian/project/project/project/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:314:20)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
You can pass string as json keys
{
"name" : req.body.name,
"title" : req.body.title,
"title2" : req.body.title2
}

Unable to find index for $geoNear query even using index

I'm using 3.6.5(mongodb) and trying to get documents near specified location like [-10, 20]...
When I tried get request "http://localhost:3030/ninjas?lng=-80&lat=20" it returns "unable to find index for $geoNear query"
I tried adding index(), changing query and searching official document but, failed.
please help!
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
app.use(bodyParser.json());
mongoose.connect("mongodb://localhost/gpsTest")
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error(('Could not connect to MongoDB...\n'), err))
const NinjaSchema = new Schema({
name: {
type: String,
},
rank: {
type: String,
},
available: {
type: Boolean,
default: false
},
geometry: {
type: {
type: String,
default: "Point",
index: '2dsphere'
},
coordinates: {
type: [Number]
}
}
})
NinjaSchema.index({geometry: '2dsphere'});
const Ninja = mongoose.model('ninja', NinjaSchema);
app.post('/ninjas', (req, res) => {
Ninja.create(req.body).then(ninja => {
res.send(ninja);
})
})
app.get('/ninjas', (req, res) => {
Ninja.find({}).where('location').nearSphere({center: {
type: 'Point',
coordinates : [parseFloat(req.query.lng), parseFloat(req.query.lat)],
spherical: true
}}
).then(ninjas => {
res.send(ninjas);
});
})
app.listen(3030, () => {
console.log(`listening port: 3030`);
})
This one is for post request.
{ "name": "test", "rank": "red belt", "available": true,
"geometry" : {"type": "Point", "coordinates": [-80, 27]} }
This is because of typo...
Should change
Ninja.find({}).where('location').nearSphere({center: {...
to
Ninja.find({}).where('geometry').nearSphere({center: {...

MongoDB query won't return object in my Express API (React)

I have done this so many times before, but I can't seem to find the issue, it's probably something small and stupid. Take a look at the /server.js file here! (Shortened for demonstration purposes)
/* Make Mongoose promise based */
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost:27017', options);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
/* Routes */
app.route('/games')
.post(postGame)
.get(getGames);
app.route('/games/:id')
.get(getGame)
.delete(deleteGame);
app.route("*").get((req, res) => {
res.sendFile('client/dist/index.html', { root: __dirname });
});
const port = 8080;
app.listen(port, () => {
console.log(`Connected! Server listening on port: ${port}`);
});
Then for my Game model, I have that in app/models/game.js.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const gameSchema = new Schema(
{
name: {
type: String,
required:true
},
year: {
type: Number,
required:true
},
description: {
type: String,
required:true
},
picture: {
type: String,
required:true
},
postDate : { type: Date, default: Date.now }
}
);
export default mongoose.model('Game', gameSchema);
This is where I believe I am having the issue.
/* Import Game model schema */
import Game from '../models/game';
const getGames = (req, res) => {
Game.find({}, (err, games) => {
console.log(err, games)
if (err) {
res.send(err);
}
res.json(games);
});
}
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
const postGame = (req, res) => {
let game = Object.assign(new Game(), req.body);
game.save(err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully created!' });
});
};
const deleteGame = (req, res) => {
Game.remove(
{ _id: req.params.id },
err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully deleted!' });
}
);
};
export {
getGames,
getGame,
postGame,
deleteGame
};
Just do be clear... I went into the mongo shell.
I did...
connecting to: test
> db.createCollection('Game')
> db.Game.insert({name: "SSB", year: 2001, description: "Fun Game", picture: "http://google.com", postDate: "2017-01-03T08:51:45.888Z"});
And when I type > db.Game.find({}); I am returned with exactly what I have...
{
"_id" : ObjectId("58c2223e32daa04353e35bdc"),
"name" : "SSB",
"year" : 2001,
"description" : "Fun Game",
"picture" : "http://google.com",
"postDate" : "2017-01-03T08:51:45.888Z"
}
You see when I go to http://localhost:8080/games I am returned with an empty JSON and I just wanna know why. I am 70% sure, it is because it isn't connected to the right collection but I don't remember how to test that :(
I wanted to make this a comment but it won't let me because I don't have a 50 reputation, but I believe I found the issue.
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
In this piece of code you are setting the id to req.params, but you need to set it to req.params.id which is what you passed in your route.
Should look like this:
const {id} = req.params.id;
If you logged id, you would probably get an object that says:
{ id: "[whatever_id_you_put_here]" }
however if you log req.params.id you should get the correct id you put in that spot..
The reason you're getting [] is because you're actually connected to the database and you are actually trying to "get" something, but that something doesn't exist so it sends an empty response.
I hope this helps..

on the server is not added "isAdmin" : true,

I want to ask you for help.
App running on localhost great.
but on the server is not added "isAdmin" : true, to the mongoDB. When you add admin.
Why? Where is the problem ?
localhost:
{
"_id" : ObjectId("57b174723e755f5dfe36d8b0"),
"salt" : "63855ff664682ad1e8ed77ded97ca5b92da472e9f0f7d68dcb058f35e71d38a4",
"hash" : "03da57be47c9ab1c9657ae9cd5ac3d8b63d56c808e28b51d6f5166bf27d8df99a2e6c25d809fcbd2436b5b883b4a64bd835ea588348d920346d9b3b601c965b90ff23b67687118b56a2b3e35343eb4b693131f7f51f7d1c9bdb4989364477b237f49d496505592564a5c3d88a0b559dc65e5543df06e4c22da50589e6551b69c2406db093a7ef78d31bc8bb8a5423ed4b677913642e0cd335992d222c49e5c58c3450068bd5a2e1cab82a9f73829f695b4686bc76f52c76e0b6ea4f248cb7e8663a96900e5d845773f3a4f09f7988a6ae24fbbdbb0ca7e670a51acd3f9b8c06f533b8c851c40680bd7156d00fe1407acf4879d8095591e8dce3a5379e041a90acb04edecafb38b0093e20db5dc41cd803ae70f351c9e8146d0e959d10114e586a370cd8063e47cc29367af9574e1a20d3973ab4be8d5a16b8a35d89c3534cdf745adfc65cd1d769811a421ea9654884dee289807e518b7eb7ba4c3e5f59242f98df6ccb3f09a9824e8679aec579a8c9a1498fc5819a2e1e8ab2f3cbf866f0e736e5c0b855d9d0f80b462fd50bf7ebf402530aaed84d6f7db5885098124ffa225563517c276563fd7eb3b058cb1f2472896a0b322bdd3b552229a677c45847667b952807ab873e5d2356297514c85cd4c3b3fac3bc3ac16d93033546fa9096e4b738f7eabd1c3494f902d0817b977116f612b3ee9040e0f9cab7e35543a42dc30",
"username" : "mail#gmail.com",
"displayName" : "Admin",
"isAdmin" : true,
"__v" : 0
}
server:
{
"_id" : ObjectId("57b174723e755f5dfe36d8b0"),
"salt" : "63855ff664682ad1e8ed77ded97ca5b92da472e9f0f7d68dcb058f35e71d38a4",
"hash" : "03da57be47c9ab1c9657ae9cd5ac3d8b63d56c808e28b51d6f5166bf27d8df99a2e6c25d809fcbd2436b5b883b4a64bd835ea588348d920346d9b3b601c965b90ff23b67687118b56a2b3e35343eb4b693131f7f51f7d1c9bdb4989364477b237f49d496505592564a5c3d88a0b559dc65e5543df06e4c22da50589e6551b69c2406db093a7ef78d31bc8bb8a5423ed4b677913642e0cd335992d222c49e5c58c3450068bd5a2e1cab82a9f73829f695b4686bc76f52c76e0b6ea4f248cb7e8663a96900e5d845773f3a4f09f7988a6ae24fbbdbb0ca7e670a51acd3f9b8c06f533b8c851c40680bd7156d00fe1407acf4879d8095591e8dce3a5379e041a90acb04edecafb38b0093e20db5dc41cd803ae70f351c9e8146d0e959d10114e586a370cd8063e47cc29367af9574e1a20d3973ab4be8d5a16b8a35d89c3534cdf745adfc65cd1d769811a421ea9654884dee289807e518b7eb7ba4c3e5f59242f98df6ccb3f09a9824e8679aec579a8c9a1498fc5819a2e1e8ab2f3cbf866f0e736e5c0b855d9d0f80b462fd50bf7ebf402530aaed84d6f7db5885098124ffa225563517c276563fd7eb3b058cb1f2472896a0b322bdd3b552229a677c45847667b952807ab873e5d2356297514c85cd4c3b3fac3bc3ac16d93033546fa9096e4b738f7eabd1c3494f902d0817b977116f612b3ee9040e0f9cab7e35543a42dc30",
"username" : "mail#gmail.com",
"displayName" : "Admin",
"__v" : 0
}
Model
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
password: String,
displayName: String,
isAdmin: Boolean
}, {
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
User.virtual("token").set(function(token) {
this._token = token;
}).get(function() { return this._token; });
User.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", User);
RegisterController
app.controller("RegisterController",
[
"$scope", "$location", "Account", "Session",
function($scope, $location, account, session) {
$scope.registerForm = {
name: undefined,
email: undefined,
password: undefined,
confirmPassword: undefined,
errorMessage: undefined
};
$scope.register = function() {
account.register($scope.registerForm.name, $scope.registerForm.email, $scope.registerForm.password, $scope.registerForm.confirmPassword)
.then(function(res) {
session.setUserData(res);
$location.path("/");
}, function(response) {
$scope.registerForm.errorMessage = response.message;
});
};
}
]);
Service session
app.factory("Session", ["$http", function ($http) {
return {
getToken: function() {
var value = sessionStorage.getItem("token");
if (value) return value;
return undefined;
},
getEmail: function() {
var value = sessionStorage.getItem("email");
if (value) return value;
return undefined;
},
getIsAdmin: function() {
var value = sessionStorage.getItem("isAdmin");
if (value) return value == "true";
return undefined;
},
setUserData: function(user) {
sessionStorage.setItem("token", user.token);
sessionStorage.setItem("email", user.username);
$http.defaults.headers.common["Authorization"] = "Bearer " + user.token;
if (user.isAdmin) {
sessionStorage.setItem("isAdmin", "true");
}
},
clear: function() {
sessionStorage.clear();
$http.defaults.headers.common["Authorization"] = undefined;
}
};
}]);

Mongoose find() returning array empty

I have the following product model:
'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
// create a schema
let produtoSchema = new Schema(
{
descricao: { type: String, required: true },
gateways: [ { type : mongoose.Types.ObjectId, ref: 'Gateway' } ]
}
);
mongoose.model('Produto', produtoSchema);
The the following collection:
rs0:PRIMARY> db.produtos.find().pretty()
{
"_id" : ObjectId("55fef1a3d7c6912033f2da72"),
"descricao" : "Product description",
"gateways" : [
ObjectId("55fee8a97cb7db7740acb322")
]
}
rs0:PRIMARY>
So, I'm trying to use Mongoose to fetch a specific product, but 'gateway' array is empty :
let Produto = mongoose.model('Produto');
Produto.find(
{
_id: mongoose.Types.ObjectId("55fef1a3d7c6912033f2da72")
}, function(err, result)
{
if (err) console.log(err);
console.log(result);
});
And the result is :
[ { _id: 55fef1a3d7c6912033f2da72,
descricao: 'Product description',
gateways: [] } ]
A also tried, but with the same result:
Produto
.find( { _id: mongoose.Types.ObjectId("55fef1a3d7c6912033f2da72") })
.populate('gateways')
.exec(function(err, result)
{
if (err) console.log(err);
console.log(result);
});
Any idea of what I'm doing wrong ?
Thanks.
I've found the problem.
I've changed:
gateways: [ { type : mongoose.Types.ObjectId, ref: 'Gateway' } ]
by
gateways: [ { type : mongoose.Schema.ObjectId, ref: 'Gateway' } ]
What's the difference between them ?