I tried mongoose find, why is [ ] being printed? - node.js

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

Related

.find() function in mongoose returns null in node js

I am simply trying to retrieve all the document from the database but I am getting empty array. I am using express, mongodb and mongoose.
Below is my code :
const express = require('express');
const countryArray = require('../models/countryArray');
const router = express.Router();
router.get('/',(req,res)=>{
countryArray.find({ },function (err, result) {
if (err)
return console.error(err);
console.log(result);
});
res.render('index');
});
module.exports = router ;
My Schema is this:
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var countrySchema = new Schema({
country_id:String,
country_name:String
});
var countryArray = mongoose.model('countryArray',countrySchema);
module.exports = countryArray;
Below is my document in mongodb:
{
"_id": {
"$oid": "5bba2693e7179a6602f63589"
},
"country_id": "1",
"country_name": "India"
}
I'm not completely sure, but I think the following may be related/helpful: Naming your model.
Afaik it goes beyond being just a "good practice", but I think the model name (countryArray) should be in PascalCase. (CountryArray, instead of countryArray)
var countryArray = mongoose.model('countryArray',countrySchema);
Hope this helps.

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

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.

What is the best way to hook to existing mongoose.model

I have a project with multiple self contained mongoose model files. I have another modelprovider which uses the model name and the request to perform an operation. I want to hook the operation to the pre of 'find'
model file
'use strict';
// load the things we need
var mongoose = require('mongoose');
var config = require('../../config/environment');
var auth_filter = require('../../auth/acl/lib/queryhook');
var modelProviders = require('../../auth/acl/lib/modelprovider');
var invoice_db = mongoose.createConnection(config.mongo.url + '/invoiceDB'); //connect to buyer DB
var path = require('path');
// define the schema for our invoice details model
var invoicedetailSchema = new Schema({
//SCHEMA INFO
});
var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);
//REGISTER THE HOOKS TO THE MDOEL
auth_filter.registerHooks(InvoiceModel);
promise.promisifyAll(InvoiceModel);
promise.promisifyAll(InvoiceModel.prototype);
module.exports = InvoiceModel;
modelProviders().setModel(InvoiceModel.modelName, path.resolve(__dirname, __filename) );
I know the hooks to find and findOne works only at the schema level but i want to be done at the model level.
registerhooks
'use strict';
var hooks = require('hooks'),
_ = require('lodash');
var mongoose = require('mongoose');
exports.registerHooks = function( model) {
var Qry = mongoose.Query;
var query = model.find();
var Sch = mongoose.Schema;
var schema = model.schema
_.assign(model, hooks);
model.hook('find', mongoose.model.prototype.find)
model.pre('find', function(next){
console.log('hell')
return next()
})
console.log(model)
};
exports.registerHooks_ = function( model) {
var Qry = mongoose.Query;
var query = model.find();
var Sch = mongoose.Schema;
var schema = model.schema
_.assign(schema, hooks);
schema.hook('find', query)
schema.pre('find', function(next){
console.log('hell')
return next()
})
console.log(schema)
};
I know the documentation proposes to do the pre and post at the schema level but is there any way to use the hooks library or the hooker library to solve this problem.
The reason i want to keep it at the model level is I need to access the model name at the 'find' pre hook. If there is a way to do so then it will be awesome

express mongoose router query

Am trying to return all item with store name ,using the conditional query method ,but the it return all items insteads ,i tried the maybe my logic is wrong
because what am trying to achieve it return all data that where store name is ,is say max mart
route('api/discount/?store=storename)
and
router.route('/discount/:store')
.get(function(req,res){
Discount.find({store:req.params.store}, function(err, discount){
if (err)
res.send(err);
res.json(discount);
});
})
so i called api/discount/store ,but this return all the data ,does not make any queries
schema model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DiscountSchema = new Schema({
store: String,
location : String,
discount : Number,
});
module.exports = mongoose.model('Bear', DiscountSchema);
You made a wrong query. You have a route to /discounts/:discount_id and you query for store:req.params.store, and a req.params.store doesn't exists, just a discount_id

Resources