Get existing document from MongoDB with Mongoose - node.js

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

Related

Empty on collection

I have created database and have make one collection with the name staff there, I have put 3 data and it is showing on mongodb compass. But will try to fetch staff I got empty array. I am baby with this mongo db envirnment so I am unknow where did I get mess on my code.
Here, I have two files. one server.js which is main file and another is model file
server.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Staff = require("./staff");
const dbname = "mydbname";
const dbpass = "mypassword";
const dbuser = "meuser";
mongoose.connect(
"mongodb+srv://"+dbuser+":"+dbpass+"#cluster0.ovjvl.mongodb.net/"+dbname+"?retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.warn("db connection done"))
.catch((error) => console.warn("DB Not Connect", error));
Staff.find({},(err,data)=>{
if(err) console.warn(err)
console.warn("Data :",data)
})
staff.js
const mongoose = require("mongoose");
let staffSchema = new mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
name:String,
designation:String,
gender:String,
salary:mongoose.Schema.Types.Decimal128,
skills:mongoose.Schema.Types.Array})
module.exports = mongoose.model('staff',staffSchema)
While I run my app I got below ouput
db connection done
Data : []
But am expecting some data on array.
Note : For security reason, I have mention dbname,user & password is fake.

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.

Mongoose MongoDB in Production

I'm having a really weird issue where Mongoose will not perform queries against collections outside of the Model definition file when NODE_ENV=production, even when connecting to localhost.
db/default.js
const mongoose = require('mongoose');
module.exports = {
connect(url) {
mongoose.connect(url);
}
};
app.js
const db = require('./db/default');
db.connect(config.get('mongoDB.uri'));
User.model.js
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
// ...
});
const User = mongoose.model('User', schema);
module.exports = User;
test.js
// This file is required by a route
const User = require('./models/User.model');
User.find({})
.then(response => console.log(response))
.catch(err => console.log(err));
All of this works absolutely fine when NODE_ENV=dev, but as soon as NODE_ENV=production, the User.find({})... doesn't run. No errors, no success, it just doesn't run.
If I log the User = require('./models/User.model'), it is a Mongoose object.
If I run the User.find({})... code inside the User.model.js file whilst in production, that also works.
I am utterly befuddled as to why this does not work.

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

modifying results in post find mongoose hook

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.

Resources