MongoDB find() returns nothing - node.js

I am trying to query my database from the mongodb shell to retrieve all the entries. Still, my find() method returns nothing.
This is the mongoose model that I am using:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: String,
content: String,
author: { type: String, default: 'Vlad'},
postDate: { type: Date, default: Date.now }
});
ArticleSchema.methods.formatTitle = function() {
var link = this.title.replace(/\s/g, '-');
return '/article/' + link;
};
ArticleSchema.methods.snapshot = function() {
var snapshot = this.content.substring(0, 500);
return snapshot;
};
module.exports = mongoose.model('Article', ArticleSchema);
When loading my Express.js application in the browser, I have no issues displaying all the articles that I have added using my API. Still, I just want to go inside the mongo shell and query them. I have used the following query:
// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()
I get an empty string in return, basically a new line in the console.

Your answer is right there, in the question:
// blog is the database name (mongodb://localhost:27017/blog)
db.blog.find()
So db already refers to correct database. Instead of blog, put collection name, not db name.
db.articles.find()

Mongo shell will connect when started to the test database, you will need to change the database and then execute the find on your collection :
use blog
db.articles.find()

First you choose the db, then you find on the collection.
use blog
db.articles.find()

Related

How to query documents in mongodb using mongoose

When i try to find a document like
const p1 = Profile.find()
console.log(p1) i should get all document in that collections but i'm getting different crap.
this is my simple schema in mongodb nodejs
const ProfileSchema = mongoose.Schema({
name: String,
age: Number,
subjects: [String],
late: Boolean
});
const Profile = mongoose.model('profile',ProfileSchema);
const profile1 = Profile.find()
console.log(profile1)
Use this -
Profile.find({}, function(err, profiles) {
console.log(profiles);
});
Refer this for more details - https://mongoosejs.com/docs/api.html#model_Model.find
const profile1 = await Profile.find({});
Since Mongoose supports async/await I would make the wrapping function async and call your find function using the await syntax.
Also make a point to pass in an empty object {} to your find function when you want to return all the documents in the collection.
More information here: https://mongoosejs.com/docs/api.html#query_Query-find

Mongoose can't find any elements after changing property type

I originally have these two schemas:
var UserSchema = new Schema({
first: String,
last: String
});
var SaleSchema = new Schema({
createdAt: Date,
registeredBy: { type: Schema.ObjectId, ref: 'User' }
});
But I want to edit my SaleSchema to save the user name instead of the ID, so I changed it for:
var SaleSchema = new Schema({
createdAt: Date,
registeredBy: String
});
Next, I wanted to edit all the Sales documents and replace the user IDs on registeredBy for the user's full name, but I can't seem to be able to perform a find query for the old ID's.
Long story short, this query returns no matches on mongoose, but it works perfectly using the mongo console:
Mongoose
Sale.find({ registeredBy: '57ea0cbb47431f0b43b87d42' })
.then(results => res.json(results))
.catch(err => res.status(500).json(err));
// result: []
MongoDB console
db.sales.find({ registeredBy: '57ea0cbb47431f0b43b87d42' })
// result: 8 elements
After I modify my schema's property back to ObjectId, the mongoose query works again. Since I need to migrate to a new datatype, I want to be able to query and store both types of values. Is this possible?
Good question this is a complicated edge case. I am not super familiar with Mongoose specifically, but one way to do this would be to migrate your data at a lower level. For example, create a mongo script that uses the low-level mongo API to do the migration, something along the lines of:
db.sales.find().forEach(function(doc){
var user = db.users.find({ _id: doc.registeredBy });
db.sales.update({ _id: doc._id, }, {
$set: { registeredBy: user.first + ' ' + user.last }
});
});
This is similar to what a module like https://github.com/balmasi/migrate-mongoose does, but I've personally found it easier to use mongo scripts on the cli directly.
mongo < sale-schema-migration.js

Mongoose ODM use

I read an article in this link http://theholmesoffice.com/mongoose-and-node-js-tutorial/
here there is a code:
exports.teamlist = function(gname,callback){
db.once('open', function(){
var teamSchema = new mongoose.Schema({
country: String,
GroupName: String
});
var Team = db.model('Team', teamSchema);
Team.find({'GroupName':gname}, function (err, teams) {
if(err){
onErr(err,callback);
}else{
mongoose.connection.close();
console.log(teams);
callback("",teams);
}
})// end Team.find
});// end db.once open
};
Here it calls db.once method whereas in other places its used like this
var mongoose = require('mongoose')
,Schema = mongoose.Schema
,ObjectId = Schema.ObjectId;
var postSchema = new Schema({
thread: ObjectId,
date: {type: Date, default: Date.now},
author: {type: String, default: 'Anon'},
post: String
});
module.exports = mongoose.model('Post', postSchema);
In the router part its used like this
exports.show = (function(req, res) {
Thread.findOne({title: req.params.title}, function(error, thread) {
var posts = Post.find({thread: thread._id}, function(error, posts) {
res.send([{thread: thread, posts: posts}]);
});
})
});
And in the app.js there is
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/norum');
I dont understand why these two have different approach and which one is the better one and why? Can Anyone please help me. One thing that I have observed is that the second approach is the one most used. SO please help me as to which one is a better approach.
I know this is mainly concerned regarding creation of the schemes in Mongodb, and so the once method looks little better. But still I am not at all sure. Please help.
Basically, in the first approach - it mearly shows you what you can do with the mongoose. It presumes that somewhere you were opening a connection to the database (presumably a few string of code back). Then it listens to the event and does all the job later. It's only there to show you what you can do.
For intance, this creates a mongoose model (it doesnt rely on the database connection being open) - hence it could be included from a separate file with ease and generally be written as a module as it is in the second approach
var teamSchema = new mongoose.Schema({
country: String,
GroupName: String
});
var Team = db.model('Team', teamSchema);
Later on in the first approach you close the connection to the database, but thats not the thing you would want to do in the real application. You have a connection pool, and use it to frequently query the database, closing the connection is only needed when you plan to stop the application from running.
Team.find({'GroupName':gname}, function (err, teams) {
if(err){
onErr(err,callback);
}else{
mongoose.connection.close();
console.log(teams);
callback("",teams);
}
First line - you perform find on the database, if no err was returned - you close the connection, log the results, etc..
Anyway, to sum up - first approach is generally a show-off, second - is what its like in a real world - where you separate logic, make models reusable and includable, where you have router logic

What does the connect command do when using Mongoose (using it in a node.js environment)?

I'm new to mongoose and am having trouble starting out. All I want to do is store some values, and retrieve all values. Right now, I'm just trying to get a base example working. Here's my code right now:
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/my_database');
var Schema = mongoose.Schema;
var IPhoneDevice = new Schema({
fbId : { type: String }
, deviceToken : { type: String }
});
var IPhone = db.model('IPhone', IPhoneDevice);
var u = new IPhone();
u.fbId = 'John';
u.save(function(){
log.debug("Saving");
});
IPhone.find({}).all(function(array){
log.debug("Finding stuff");
});
The problem is, it never prints out anything. I think it might be something to do with the mongoose connect line. I just copied this from an example, but does there need to be a file on my localhost where the database is stored? I don't have any file called my_database anywhere...do I need to create one?
I would write the last call like this:
IPhone.find({}, function (err, docs) {
console.log(docs);
});
mongoose needs the query in the find, then a callback to handle the returned documents or the error.
See: Finding Document with Mongoose

What are Mongoose (Nodejs) pluralization rules?

I am a newbie to the Node.js, Mongoose and Expressjs. I have tried to create a table "feedbackdata" using the Mongoose in MongoDB via the following code. But it is created as "feedbackdata*s*". By Googling, I found that the Mongoose uses pluralization rules. Anyone please help me to remove the pluralization rules? or how my code should be for the "feedbackdata" table?
Below is my code:
app.post("/save",function(req,res){
mongoose.connect('mongodb://localhost/profiledb');
mongoose.connection.on("open", function(){
console.log("mongo connected \n");
});
// defining schemar variables
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
// define schema for the feedbackdata table
var feedback_schema = new Schema({
_id: String,
url:String,
username:String,
email:String,
subscribe:String,
types:String,
created_date: { type: Date, default: Date.now },
comments: String
});
// accessing feeback model object
var feedback_table = mongoose.model('feedbackdata', feedback_schema);
var tableObj = new feedback_table();
var URL = req.param('url');
var name = req.param('name');
var email = req.param('email');
var subscribe = req.param('subscribe');
var choices = req.param('choices');
var html = req.param('html');
var receipt = req.param('receipt');
var feedbackcontent = req.param('feedbackcontent');
tableObj._id = 3;
tableObj.url = URL;
tableObj.username = name;
tableObj.email = email;
tableObj.subscribe = subscribe;
tableObj.types = choices;
tableObj.comments = feedbackcontent;
tableObj.save(function (err){
if(err) { throw err; }else{
console.log("Saved!");
}
mongoose.disconnect();
})
res.write("<div style='text-align:center;color:green;font-weight:bold;'>The above values saved successfully! <br><a href='/start'>Go back to feedback form</a></div>");
res.end();
});
The pluralization rules are in this file: https://github.com/LearnBoost/mongoose/blob/master/lib/utils.js
You can add your schema name to the 'uncountables' list, then mongoose will not pluralize your schema name.
Provide the name for the collection in options while creating schema object, then Mongoose will not do pluralize your schema name.
e.g.
var schemaObj = new mongoose.Schema(
{
fields:Schema.Type
}, { collection: 'collection_name'});
For more Info: http://mongoosejs.com/docs/guide.html#collection
The pluralization rules is here to ensure a specific naming convention.
The collection name should be plural, all lowercase and without spacing.
What are naming conventions for MongoDB?
I think you should ask yourself if you want to follow the main rule (ensured by mongoose as a default behavior) or get rid of it.
What are the perks ? What are the good points ?
You design first what is an user (User model) and then you store users into a collection. It totally make sense.
Your call.
If you ask yourself how to get the final name of the collection after the pluralization :
const newName = mongoose.pluralize()('User');

Resources