Mongoose save fail without error - node.js

I got success message, without document creation.
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var conn = mongoose.createConnection(mongodb://localhost:27017/social_media);
var testModel = conn.model('test', new mongoose.Schema({
key: { type: String, required: true }
}));
var test = new testModel();
test.key = 'hello';
test.save().then(function(tmp) {
console.log('success');
console.log(tmp);
}).catch( function() {
console.log('failure');
});
As a result I get in console 'success' message with created object - so as I assume, document should be successfully inserted. In the moment of code run, database and collection don't exist. After code run, only db is created.
I tried to change 'createConnection' to 'connect' without any result.
I have already checked plenty of similar answers, but still can't find solution.
I'm using MongoDB v3.2.8, node.js MongoDbDriver v2.2.5 and Mongoose v4.5.8

The fault was in used GUI. I was using RoboMongo v0.8.5 and MongoDb v.3.2.8. The problem is that RoboMongo in that version is not supporting used MongoDb version. The full suport for mongo 3.x, came with RoboMongo v.0.9.0 - http://blog.robomongo.org/robomongo-rc1-with-full-support-for-mongodb-3/

Related

The records can be inserted in the db and can be fetched (with mongoose), but when I log into the mongodb, it is empty

I am following this tutorial to understand how mongoose interacts with mongodb: http://blog.modulus.io/getting-started-with-mongoose
I have created a schema and a model. When I save the data, I get a console callback, that gives me out everything, I have saved. When I find the information, it also gets logged out. But when I log into mongo via terminal, use the mydb and execute the query db.mydb.find().pretty(), I get no results.,
What might be the problem? I am using exactly the same code, as in the tutorial.
This is the code, in case it will help to find the problem, somehow:
This is in the app.js
var db = mongoose.connection;
// console errors
db.on('error', console.error);
// load models
db.once('open', function() {
fs.readdirSync(__dirname = './models/').forEach(function(filename) {
if(~filename.indexOf('.js')) {require('./models/' + filename)};
});
});
mongoose.connect('mongodb://localhost/mydb');
*So it basically creates the connection, loads all of the models from the folder and consoles an error, if it occures (it does not).
Here is the code from my user model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var usersSchema = new Schema({
name: String,
age: Number,
admin: Boolean
});
var User = mongoose.model('Users', usersSchema);
Here I insert the user:
var danny = new User({
name: 'Danny',
age: 25,
admin: true
});
danny.save(function(err, res) {
if (err) { return console.error(err) };
console.dir(res);
});
*It logs out this user, when saved.
If I find all the users, I get the list of the same user (because It was accidentally saved multiple times). To find all, I use this command:
User.find(function(err, res) {
console.dir(res);
});
If I log in mongodb using command mongo on my Ubuntu Linux, and then I switch to the database with command use mydb and then db.mydb.find().pretty() It prints out nothing
You are making a small mistake when querying the database through the Mongo shell. Instead of using db.mydb.find().pretty(), you should use db.users.find().pretty().
Here is why:
You are connecting to your database with this line in Mongoose:
mongoose.connect('mongodb://localhost/mydb');
The mydb at the end will be the name of your database. So you might want to change this to something else so it is easier to recognise the database in the future.
In the Mongo shell, you are switching your database correctly using use mydb. To query your collection, you will need the following syntax:
DB + collection name + command() + extra stuff();
This means you will get the following command:
db.users.find().pretty();
The reason you should be using users, is because of this line:
var User = mongoose.model('Users', usersSchema);
Users will be the name of your collection. Please note that if you used User, Mongoose would have added an "s" to your collection name. To overwrite this, you can use this line:
usersSchema('collection', 'user');
Now your collection will always get the name user.

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.

mongodb + mongoose: query not entering .find function

I am getting start with mongodb and mongoose but am having problems querying a database. There are a number of tutorials online for what I am trying to do but it just doesn't seem to work for me. My problem is that the .find() function is not even being called and the collection is not being displayed. I have a collection called Subjects in which I know there are some values (I manually entered them in the mongodb command line). I only tried including pertinent code but let me know if anything else is needed. Thanks in advance.
app.js file
require('./models/model.js');
var conn = mongoose.createConnection('mongodb://localhost/test');
var Subject = mongoose.model('Subjects');
Subject.find( { }, function (err, subjects) {
if(err) console.log("Error"); // There is no "Error"
console.log("Made it"); // There is no "Made it"
console.log(subjects);
});
model.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SubjectsSchema = new Schema ({
subject: { type: String }
});
module.exports = mongoose.model('Subjects', SubjectsSchema);
Call mongoose.connect instead of mongoose.createConnnection to open the default connection pool that will be used by models created using mongoose.model:
mongoose.connect('mongodb://localhost/test');

MongoDB find() returns nothing

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

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

Resources