modifying results in post find mongoose hook - node.js

I am trying to find a way to modify the query results of mongoose.
Below is the self contained model with the post hook
'use strict';
// load the things we need
var mongoose = require('mongoose');
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
});
invoicedetailSchema.post('find', function(results){
console.log('POST FIRED')
results = results.filter(function(doc){
return doc.tags.length;
})
})
var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);
// create the model for seller and expose it to our app
promise.promisifyAll(InvoiceModel);
promise.promisifyAll(InvoiceModel.prototype);
module.exports = InvoiceModel;
The find query is working fine and the post is firing but the results are not filtered per the post hook.
How do i go about editing the results before the results are returned.

Related

Get existing document from MongoDB with Mongoose

I have an existing document on MongoDB atlas that I need to get in its entirety. When I try my current code I get a socket timeout, i.e. it keeps buffering.
There is only one document in my collection.
My theory is that the error is in my Mongoose Schema, but I don't know what to put there since I don't want any "filters", I want everything.
The name of the collection in Atlas is Playstation and the id of the document I want to get is: 5f5e2d281386efc27bb3ce45
const express = require('express')
const router = express.Router()
const Playstation = require('../models/playstation')
//Getting All
router.get('/', async (req, res) => {
try {
const playstations = await Playstation.findById("5f5e2d281386efc27bb3ce45")
res.json(playstations)
} catch (err) {
res.status(500).json({ message: err.message })
}
})
module.exports = router;
My schema & model:
const mongoose = require('mongoose')
const playstationSchema = new mongoose.Schema({
})
module.exports = mongoose.model('Playstation', playstationSchema)
I believe the problem is your mongoose schema. What you want is a schemaless collection, since you dont want to define the schema, and you want everything in the document, you can define the collection as schema-less, with strict:false option in your mongoose schema;
Try this:
const mongoose = require('mongoose')
const playstationSchema = new mongoose.Schema({
},{ strict : false })
module.exports = mongoose.model('Playstation', playstationSchema);
You can read more about this option on Mongoose Documentation

getting empty array in response res.json(); in nodejs code

Why does res.json respond with an empty array?
I want to get all data from collection distributor ,so for that I have
created model file and then assigned it to on variable Distributordata
Server file : app.js
var express=require('express');
var app=express();
var bodyParser=require('body-parser');
var mongoose=require('mongoose');
var Distributordata=require('./distributor.model');
var db='mongodb://localhost/Distributordata';
mongoose.connect(db);
var port=8080;
app.get('/',function(req,res){
res.send("happy to be here");
});
app.get('/distributor',function(req,res){
// res.send("hi from distributors")
console.log("getting all distributors");
Distributordata.find(function(err,distributordata){
if(err){
res.send("error has occured");
}
else{
console.log(distributordata);
res.send(distributordata);
}
});
});
app.listen(port,function(){
console.log('app listening on port'+port);
});
Model file : distributor.model.js
var mongoose=require('mongoose');
var Schema = mongoose.Schema;
var DistributorSchema=new Schema({
dname:String,
daddress: String
});
module.exports=mongoose.model('Distributordata',DistributorSchema);
output
on cmd:
app listening on port8080
getting all distributors
[ ]
So far I've understood your problem is you are creating your collection in mongodb by yourself as the collection name distributor. And also as you are not sending any post request so your code will not create any collection automatically in the main database.
But, by default mongoose always creates a collection name by pluralizing the name of the model, in your case this collection name would be distributordatas. But when, you are trying to get the data from your database, it's getting the collection name as distributor for this reason it becomes unable to make a connection. But you can keep this using force naming convention for collection as like you want.
In your distributor.model.js file change this line of code to this one:
module.exports = mongoose.model('Distributordata', DistributorSchema, 'distributor');
Hopefully, it'll solve your problem. For more reference check this out https://mongoosejs.com/docs/guide.html#collection

How does mongoose model connect with mongodb?

I have structured a user collection using mongoose.model().This model exist in seperate file called as model\user.js. The mongodb connection instance (using mongoose) exist in seperate file db\mongoose.js. Both of these files are imported into server.js to work with web application.
var express = require('express');
var bodyParser = require('body-parser');
var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');
var app = express();
app.use(bodyParser.json());
app.post('/todos', (req, res) => {
var user = new User({
text: req.body.text
});
user.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
The {mongoose} and {User} seems to be a separate entities and model\user.js didn't import ./db/mongoose.js as well . The user model being static content , how does user.save() connects with db and save the document?
First of all let me tell you what is happening in your project.
in Mongoose file:
You have DB connection with Mongoose.
Now Mongoose has your DB connection.
That is the reason it is imported in server.js file.
Secondly, in you model/user.js you have
Declared Schema using Mongoose.
user.save method.
When you use Mongoose here (or any DB related query), it points to your connected DB. Which does not require any explicit connection written in some file.
For more details read Mongoose Docs.
Hope I cleared your thoughts.

how to use mongodb indexing in nodejs application

I am trying to build a search module using mongodb indexing but not sure how to use it on the collection created using mongoose
i.e,
db.books.createIndex({"Title":"text"}) this works fine in mongo shell
where books is a collection which is inside database called bookish
but how to use it in nodejs application where i have few apis calls defined
var express = require('express');
var mongoose = require('mongoose');
router = express.Router();
var cors = require('cors');
module.exports = function (app) {
app.use(router);
};
/*+++++++++++++++++++++++++++++++++++++++++ Defining Model Starts++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
Books = mongoose.model('Books');
/*+++++++++++++++++++++++++++++++++++++++++ Defining Model Stops++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*+++++++++++++++++++++++++++++++++++++++++ Router Starts++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
router.route('/api/book/')
.get(function(req,res){
Books.find({},function(err,books){
console.log( req.params.id);
res.send(books);
})
});
router.route('/api/delete/book/:id')
.post(function(req,res){
console.log("delete id"+req.params.id)
Books.findOne({bookId: req.params.id}, function(err,updateRemoveBook) {
updateRemoveBook.isDeleteBook= 0;
updateRemoveBook.save();
res.send(updateRemoveBook);
});
});
router.route('/cerateIndex')
Books.createIndex({"subject":"text","content":"text"})
in this file how to create index on this book ie here books is a refrence of model but create Index should be called on the collection right
i am not able to do like
db.Books.createIndex({"subject":"text","content":"text"})
i am referring this article to perform indexing
http://code.tutsplus.com/tutorials/full-text-search-in-mongodb--cms-24835
not sure how to use it with nodejs application please provide suggestion to how to go about it point some sample which can demonstrate the same
You can create the text indexes using the model schema's index() method:
bookSchema = new mongoose.Schema({"subject": String, "content": String},{"collection": "books"});
bookSchema.index({ "subject": "text", "content": "text" });
Books = mongoose.model('Books', bookSchema);

Why am I only getting the content of one of my items?

I have a simple comments app which enables the user to enter a comment into the system via a form and these are then logged onto a list on the bottom of the page.
I wanted to modify it so that a user could click a comment once it is created and it would load up the associated content that goes with that comment.
My schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
title: String,
content: String,
created: Date
});
module.exports = mongoose.model('Comment', CommentSchema);
My app.js routes:
app.use('/', routes);
app.use('/create', create);
app.use('/:title', show);
My show route:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment', Comment);
router.get('/', function(req, res) {
Comment.findOne(function(err, comment){
console.log(comment.content)
});
});
module.exports = router;
I have three comments in my system and saved in my database, each with unique contents, But whenever I click on a comment, no matter what it is. I am only getting the content that is associated with the first comment.
Why is this?
You'll have to provide a condition for .findOne() to retrieve a specific document:
Model.findOne(conditions, [fields], [options], [callback])
Without one, an empty condition is implied that matches every document in the collection:
Comment.findOne({}, function ...);
And, .findOne() simply retrieves the 1st of those that are matched.
With the :title parameter in the route for show and title property in the Schema, one possible condition would be:
Comment.findOne({ title: req.params.title }, function ...);
Though, if the titles aren't unique in order to find the "right" one, you'll have make the condition more specific. The _id or id would be the most distinct.
app.use('/:id', show);
Comment.findOne({ id: req.params.id }, function ...);
// or
Comment.findById(req.params.id, function ...);
Also adjusting any links and res.redirect()s to fill pass the id for :id.

Resources