Imported mongoose model cannot perform operations - node.js

I have created a mongoose model in a file User.js:
var mongoose = require('mongoose');
exports.GetUser=function(conn){
var UserSchema = mongoose.Schema({
username: String,
age: Number
},{collection:"User",versionKey: false});
var usermodal = conn.modal("User",UserSchema);
return usermodal;
}
I am importing and using it in test.js file like this:
var user = require('./User.js');
var mongoose = require('mongoose');
var conn = mongoose.createConnection(\\connection string and other config here);
var userModal = user.GetUser(conn);
userModal.find({},(err, result)=>{
console.log(result); //prints undefined
});
The result comes undefined here. When I moved the model inside test.js, it started working and fetched data from the collection correctly. I cannot find what is the issue here. There are other models as well in User.js which I am exporting and using in the same way but they are also not working.
Please help me to find the issue and correct it. Thanks!

Related

mongoose query doesn't return the actual object

I have added a method to my mongoose scheme. When I create an instance, I can call that object but when I query for that object and try to call the same method, it returns exception.
User.js file:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String
surname: String
});
userSchema.methods.print = function() {
console.log(this.name, this.surname);
};
module.exports = mongoose.model('User', userSchema);
The following code works as expected:
const user = new User({});
user.print();
But when I query mongodb and try to call print on the method it returns exception:
User.findById(id, function(err,user){
// print is not a function
user.print();
});
I can't see where I'm making mistake,
And suggestions ?
Thanks.
It is because you haven't created an object of User.
Change module.exports = mongoose.model('User', userSchema); to let User = module.exports = mongoose.model('User', userSchema); in the User.js file and create an object of User before calling the print method, like:
let User = require('<path>/User.js'); where you need to update path with the actual path of the file.

Querying result from mongoose using dynamic model.find

I need to find the results of a query with mongoose find({}) method in Node.js with a variable containing model name.
var adSchema = new Schema({ schema defination });
var Ad = mongoose.model('Ad', adSchema);
var variableName = 'Ad';
variableName.find({}).exec(function (err, adObj) {});
Is it possible or not?
Thanks in advance
You should be able to do that when calling model with just the name like so
mongoose.model('Ad').find({}).exec(function (err, adObj) {});
See here for the corresponding part of the official docs
Try this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var anySchema = new Schema({
fieldname: String
});
var Test = mongoose.model('Test', anySchema);
Test.find({}).exec(function(err,result){});

Issue with MongoDB, Node and Express-looking up ID in Mongo

I am currently working on a simple MEAN project and I am working on pulling one item out of my mongo db and show it on the web page. Whenever I go to the site
http://localhost:3000/api/events/5782b1dbb530152d0940a227 to see the information on the object, I get null displayed. I am, like I said, suppose to see information on this object. Here is what my code looks like:
controllers:
var mongoose = require('mongoose');
var Eve = mongoose.model('Info');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.eventsReadOne = function(req, res) {
Eve
.findById(req.params.eventid)
.exec(function(err, info){
sendJSONresponse(res, 200, info)
});
//sendJSONresponse(res, 200, {"status" : "success"});
};
Models:
var mongoose = require( 'mongoose' )
var eventSchema = new mongoose.Schema({
activity: String,
address: String,
});
mongoose.model('Info', eventSchema);
routes:
var express = require('express');
var router = express.Router();
var ctrlEvents = require('../controllers/events');
//events
router.get('/events/:eventid', ctrlEvents.eventsReadOne);
module.exports = router;
Now, one thing that may be noticed is that I call my mongo collection events. However, I forgot that event is a key word in JS so I tried "changing" it to Info which you will see on the last line of my model. Like I said, if I go to the site http://localhost:3000/api/events/5782b1dbb530152d0940a227, where the last number is the obj _id then I should see all of the data on it. Instead, all that I see is null. Any help would be great, thank you!
my other model file, db.js, has the connection:
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/mission';
mongoose.connect(dbURI)
require('./events');
Mongoose will use the model name to determine which MongoDB collection it should use. The default scheme is to take the model name, lowercase and pluralize it, and use the result as the collection name, which in your case (using Info as model name) would be infos:
// This is where the model is created from the schema, and at this point
// the collection name is decided.
mongoose.model('Info', eventSchema);
If you want it to use a different collection, you have to explicitly tell Mongoose what collection to use by setting the collection option for your schema:
var eventSchema = new mongoose.Schema({
activity : String,
address : String,
}, { collection : 'events' });
To fix the error you're stating in the comments (Schema hasn't been registered for model "mission"), you need to make sure that you change all occurrences of mongoose.model():
// To create the model:
mongoose.model('Mission', eventSchema);
// Later on, to access the created model from another part of your code:
var Eve = mongoose.model('Mission');
(although it seems to be that "mission" is the name of your database; because your collection is called events I would think that a model name Event seems much more appropriate)

Mongoose findById is returning null

So I have this schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TreeSchema = new Schema({
}, { collection: 'treeLocations' });
var TreeDetailsSchema = new Schema({
}, { collection: 'treeInfo' });
module.exports = mongoose.model('Tree', TreeSchema);
module.exports = mongoose.model('TreeDetail', TreeDetailsSchema, "treeInfo");
And I am calling by ID like this:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
router.route('/api/trees/:tree_id')
.get(function(req, res) {
TreeDetails.findById(req.params.tree_id, function(err, treedetail) {
if (err)
res.send(err);
res.json(treedetail);
});
});
For some reason - http://localhost:3000/api/trees/5498517ab68ca1ede0612d0a which is a real tree, is returning null
Something that might help you help me:
I was following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
The only thing I can think of that changed is that I have a collection name. Might that be it?
The step that I don't see is how you actually connect to MongoDB and after that, how you get the Model from the connection.
// connect to MongoDB
var db = mongoose.createConnection('mongodb://user:pass#host:port/database');
// now obtain the model through db, which is the MongoDB connection
TreeDetails = db.model('TreeDetails');
This last step is how you associate your model with the connected mongo database.
More info on Mongoose.model
There are several ways to establish a connection to MongoDB with mongoose, the tutorial uses:
mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o');
(Personally I prefer the more explicit mongoose.createConnection as shown in the example)
(I used mongoose 4.3.1 for this example)
My steps to reproduce, in order to provide a working example (without creating a webservice for it):
var mongoose = require('mongoose'),
TreeDetails, db;
// create the model schema
mongoose.model('TreeDetails', mongoose.Schema({
// .. your field definitions
}, {collection: 'treeInfo'}));
db = mongoose.createConnection('mongodb://user:pass#host/example');
TreeDetails = db.model('TreeDetails');
TreeDetails.findById('5671ac9217fb1730bb69e8bd', function(error, document) {
if (error) {
throw new Error(error);
}
console.log(document);
});
Instead of:
var TreeDetails = require('./app/models/tree').model('TreeDetail');
try:
var mongoose = require('mongoose'),
TreeDetails = mongoose.model('TreeDetail');
Defining the collection name shouldn't give you any issues. It's just what the collection will be called in the database / when using the mongo shell.
And just to be sure, try logging req.params.tree_id before calling findById to make sure it's coming through as you suspect.

mongodb + mongoose: query not entering .find function

I am getting start with mongodb and mongoose but am having problems querying a database. There are a number of tutorials online for what I am trying to do but it just doesn't seem to work for me. My problem is that the .find() function is not even being called and the collection is not being displayed. I have a collection called Subjects in which I know there are some values (I manually entered them in the mongodb command line). I only tried including pertinent code but let me know if anything else is needed. Thanks in advance.
app.js file
require('./models/model.js');
var conn = mongoose.createConnection('mongodb://localhost/test');
var Subject = mongoose.model('Subjects');
Subject.find( { }, function (err, subjects) {
if(err) console.log("Error"); // There is no "Error"
console.log("Made it"); // There is no "Made it"
console.log(subjects);
});
model.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectsSchema = new Schema ({
subject: { type: String }
});
module.exports = mongoose.model('Subjects', SubjectsSchema);
Call mongoose.connect instead of mongoose.createConnnection to open the default connection pool that will be used by models created using mongoose.model:
mongoose.connect('mongodb://localhost/test');

Resources