I am trying to do a find with mongoose, but I get this
"TypeError: Query.find is not a function"
I have this model:
// file: ./models/request.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var dnSchema = new Schema({
customerId: String,
uuid: String,
get_data: String,
get_scores: String
});
dnSchema.index({ customerId: 1, time: -1 });
module.exports = mongoose.model('dN', dnSchema);
And I have this controller
var mongoose = require('mongoose');
var dn = mongoose.model('dn');
(...)
var getScores = exports.getScores = function(req, res) {
var Query = new dn();
console.log(Query)
Query.find({}, function(err, example) {
res.status(200).send(example)
});
}
And this index.js
var mongoose = require('mongoose');
mongoose.connect(config.url, function(err, res) {
if(err) {
logger.error('Error connecting to Database ' + process.pid);
throw err;
}
});
var models = require('./models/request')(app, mongoose);
var controllers = require('./controller/request');
var router = express.Router();
router.route('/get_scores')
.get(controllers.getScores);
app.use(router);
var httpServer = http.createServer(app);
httpServer.listen(config.port, function (){
controllers.logIn();
});
I am trying to do a simple .find, but I can do it.
I hope your help mates!!
Thanks you!!
Try to import the Schema in your controller and use that one.
var dn = require('path to schema file');
(...)
var getScores = exports.getScores = function(req, res) {
dn.find({}, function(err, example) {
res.status(200).send(example)
});
}
Related
I am using mongoose version ^5.10.2 and I've been able to save data to the mongo Atlas database BUT I can not get the data down. When I try using:
const mongoose = require('mongoose');
const express = require('express');
{
const config = require("./config.json")
var token = config.token;
var prefix = config.prefix;
var botName = config.botName;
}
const server = require('./server.js');
server();
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
modName: String,
modUrl: String
});
// Compile model from schema
var SomeModel = mongoose.model('SomeModel', SomeModelSchema);
setInterval(function () {
// Create an instance of model SomeModel
var awesome_instance = new SomeModel({ 'ModName': 'Kiddions mod menu', 'modUrl': 'https://www.unknowncheats.me/forum/downloads.php?do=file&id=27946' });
console.log('---Direct info---');
console.log('Name: ' + awesome_instance.ModName);
console.log('URL: ' + awesome_instance.modUrl);
// Save the new model instance, passing a callback
awesome_instance.save(function (err) {
if (err) return handleError(err);
// saved!
});
awesome_instance.find({}, function(err, data){
console.log(">>>> " + data );
});
}, 2000);
Server.js code:
const express = require('express');
const connectDB = require('./DB/Conncection');
const app = express();
module.exports = function server() {
connectDB();
app.use(express.json({ extended: false }));
app.use('/api/userModel', require('./Api/Mod'));
const Port = process.env.Port || 3030;
app.listen(Port, () => {
console.log('Server started')
});
}
Connection.js code:
const mongoose = require('mongoose');
const URI =My database";
const connectDB = async () => {
await mongoose.connect(URI, {
useUnifiedTopology: true,
useNewUrlParser: true
});
console.log('DB connected..!');
};
module.exports = connectDB;
It fails... I get the bug:
Server started
DB connected..!
---Direct info---
Name: undefined
URL: https://www.unknowncheats.me/forum/downloads.php?do=file&id=27946
C:\Users\zssho\Desktop\Fiverr Gigs\the_mcs - GTA modding\Discord bot\src\bot.js:45
**awesome_instance.find({}, function(err, data){
^
TypeError: awesome_instance.find is not a function
at Timeout._onTimeout (C:\Users\zssho\Desktop\Fiverr Gigs\the_mcs - GTA modding\Discord bot\src\bot.js:45:22)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
I have used this as a function for a while but it stopped working recently. Could it be because I updated mongoose?
awesome_instance is a document .find is a method present in collection/models so try
SomeModel.find({}, function(err, data){
console.log(">>>> " + data );
});
i know the question already has been asking, but i can't figure out what i am doing wrong on my code, in my '/' when i start the app the router executes my index.js file that has the following code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Loja = require('../models/lojas');
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date());
console.log('Request Type:', req.method);
console.log('Request URL:', req.originalUrl);
next(); //passa a solicitação para a próxima função de middleware na pilha
});
//get all contacts with specific filter
router.post('/registo',function(req,res){
var loja = new Loja();
loja.name = req.body.name;
loja.email = req.body.email;
loja.setPassword(req.body.password);
loja.save(function(err){
var token;
token = loja.generateJwt;
res.status(200);
res.json({
"token": token
});
});
});
my app.js looks like following:
var express = require('express');
var bodyParser = require('body-Parser');
var mongoose = require('mongoose');
var passport = require('passport');
require('./config/passport');
var app = express();
var dbName = 'LojasDB';
var connectionString = 'mongodb://localhost:27017' + dbName;
mongoose.Promise = global.Promise;
mongoose.connect(connectionString);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(passport.initialize());
app.use(function(req,res,next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-MethodOverride,Content-Type, Accept');
next();
});
app.use('/',require('./routes/index'));
app.listen(8080,function(){
console.log("listen on port 8080");
})
basicly i have a model called loja, that i want to use to authenticate, so i used passport for the first time to do this, but somehow i get a error that the schema hasn't been registred for that model, my model looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var jwt = require('jsonwebtoken');
var crypto = require('crypto');
var lojasSchema = mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
hash: String,
salt: String
});
lojasSchema.methods.generateJwt = function() {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
exp: parseInt(expiry.getTime() / 1000),
}, "12345"); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
lojasSchema.methods.setPassword = function(password){
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};
lojasSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
return this.hash === hash;
};
module.exports = mongoose.model('Loja',lojasSchema);
so i am exporting the model here, so in my router index.js i require it like this:
var Loja = require('../models/lojas');
The following line:
var lojasSchema = mongoose.Schema({
should be:
var lojasSchema = new mongoose.Schema({
Make sure you are exporting your routes from that index.js file as I see they are separate from your app.js file. You need to require your Mongoose Models in your app.js file. So add something like this in your app.js.
var Loja = require('../models/lojas');
I'm trying to setup a model but there is no data rendering on the page (using a handlebars view engine).
I have the following in an app.js file:
// Mongoose setup
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nickinumbers');
And then this is the model I setup for the data I need returned this is ina nickinumbers.js file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var NickiNumberSchema = new Schema({
number: {type: 'String', required: true},
firstName: {type: 'String'}
});
var NickiNumber = mongoose.model('Nickinumber', NickiNumberSchema);
module.exports = NickiNumber;
Finally, my index.js router file contains:
var express = require('express');
var router = express.Router();
var NickiNumber = require('../models/nickinumbers');
router.get('/', function(req, res) {
NickiNumber.find(function(err, nums) {
if (err) return console.error(err);
res.render('index', {title: 'Users', nums: nums});
});
});
module.exports = router;
I'm not seeing any errors on the server or in the console and I can't figure out why this isn't working. Any help is appreciated!
In find function first parameters is query condition then apply callback.
so you should use query condition {} to get all records or can apply your query. so should use NickiNumber.find({}, function(...
Query should be like:
var express = require('express');
var router = express.Router();
var NickiNumber = require('../models/nickinumbers');
router.get('/', function(req, res) {
NickiNumber.find({}, function(err, nums) {
if (err) return console.error(err);
res.render('index', {title: 'Users', nums: nums});
});
});
module.exports = router;
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 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);
});
})
});