Querying result from mongoose using dynamic model.find - node.js

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){});

Related

Imported mongoose model cannot perform operations

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!

I tried mongoose find, why is [ ] being printed?

I tried to output the information stored in the db, but the result is only []. Where is the problem?
route/serch.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var crodata = require('../model/cro');
router.get('/',function (req,res,next) {
var ser = req.query.word; //namsan
crodata.find({tags:{$regex:ser}} , function(err, result) {
if(err) { console.log(err)}
console.log(result);
})
//res.render('serch',result)
});
module.exports = router;
/model/cro.js
const mongoose = require('mongoose')
var Schema = mongoose.Schema;
var croSchema = new Schema(
{ index:String,content:String,data:String,like:String,place:String,tags:String}
)
module.exports = mongoose.model('cro1',croSchema);
Information stored in db
{"_id":{"$oid":"5fe916d69d46ee5848393949"},
"index":"1",
"content":"Seoul Vibes.#namsan #fstopgear #breathbaselayer ",
"data":"2020-12-27",
"like":"946",
"place":"Seoul",
"tags":"['#namsan', '#nseoultower',]"}
Be sure that req.query.word property has a value, remember that req.query shape is based on user-controlled input (should be validated before trusting).
Beside that, you query look ok, but is good to know that, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match you query statement.
More about Regex and Index

Dynamic schema keys in Mongoose

I have a simple requirement to get dynamic keys and their values to insert in mongo.
something like this:
[
{"key1": "val1"},
{"key2": "val2"}
]
For this I have created schema as :
As I read about [Schema.Types.Mixed],but it only makes datatype of assigned values dynamic ,not the key in my case.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myschema = new Schema({ key: [Schema.Types.Mixed] });
module.exports = mongoose.model('DataCollection', myschema);
Can anybody point , whtat is it that I am missing.
This is my output,which shows blank value.
Thanks in advance.
I don't think it is possible to literally have a dynamic key as that defeats the purpose of a schema, but you could do something like this:
var KeyValueSchema = new Schema({
key : String,
value : String
});
module.exports = mongoose.model('KeyValueCollection', KeyValueSchema);
Alternatively using the Mixed data type you could store an entire JSON object. For example using this schema:
var mySchema = new Schema({
data : Schema.Types.Mixed
});
module.exports = mongoose.model('DataCollection', mySchema);
You could insert like:
.post(function(req, res) {
var collection = new DataCollection();
collection.data = {'key' : 'value'};
collection.save(function(err) {
if(err) res.send(err);
res.json({message:'Data saved to collection.'});
});
});

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.

Accessing subdocument properties in mongoose

I am using a MEAN stack to build this application.
Here is my subject.js schema:
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var topics = require('./topic');
var subjectSchema = new schema({
_category : {
type: String,
default: ""
},
topics: [topics.schema]
});
module.exports = mongoose.model('Subject', subjectSchema);
and my topics.js schema:
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var otherstuff = require('./otherstuff');
var otherstuff2 = require('./otherstuff2');
var topicSchema = new schema ({
title: String,
otherstuff: [mongoose.model('otherstuff').schema],
otherstuff2: [mongoose.model('otherstuff2').schema]
});
module.exports = mongoose.model('Topic', topicSchema);
What I am having difficulty with is how to access my topicSchema to populate it with forms from my front end.
I can save information to the subjectSchema, but not the sub documents.
I have tried using this as outlined in another article:
var Subject = mongoose.model('Subject', subjectSchema);
Subject.find({}).populate('subjects[0].topics[0].title').exec(function(err, subjects) {
console.log(subjects[0].topics[0].title);
});
But I continue to get TypeError: Cannot read property 'title' of undefined. How do I access the title property?
populate in mongoose is used to populate referenced documents, that are marked with ref attribute (see more info in the docs). Sub-documents on the other hand are available when do a simple query because they are actually an array of custom objects, so if you remove the populate method your query will work as expected:
Subject.find({}).exec(function(err, subjects) {
console.log(subjects[0].topics[0].title);
});

Resources