I am trying to retrieve data from MongoDB in nodejs. The items have slightly different structure ,so I do not want to use strict schema. My code is:
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const testDataSchema = new Schema({ any: {} })
const TestData = mongoose.model('my_collection_name', testDataSchema);
var url = "mongodb://myurl";
mongoose.connect(url);
mongoose.connection.once('open', function(){
console.log('connected!!!');
}).on('error', function(error){
console.log('error!!!', error);
});
TestData.findOne({}).then(function(result){
console.log('Result', result);
})
It prints:
connected!!!
Result null
The collection defenitelly has many records. What is the problem here and how to resolve it?
Try
TestData.find(function (err, products) {
if (err) {
res.send(err);
}
console.log(products);
});
also make sure that TestData is a model object
I'm new to Node, along with Mongoose and MongoDB. I'm trying to test inserting data into one of the collections in a database on MongoDB Atlas. However, the code somehow inserts the data into the wrong database. I intend to insert data into the 'test' collection in the 'quizzard' database. However, a new collection called 'tests' was created within quizzard where the data was placed. When I tried it again, it started inserting data into another database called 'test' and created a collection called 'tests', where the data is still being placed.
var link = "mongodb+srv://<user>:<password>#quizzard-dp0b2.mongodb.net/test?retryWrites=true&w=majority";
// changed to <user> and <password> for privacy reasons
mongoose.connect(link, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('Connected');
});
const Schema = mongoose.Schema;
const TestSchema = new Schema({
_id: Number,
data: String
});
//TestSchema.set('database', 'test');
//TestSchema.set('collection', 'test');
const Test = mongoose.model('Test', TestSchema);
const data = {
_id: 11,
data: "why???"
};
const newTest = new Test(data);
newTest.save((error) => {
if(error){
console.log("An error has occured");
} else {
console.log("Action performed");
}
});
You need to change the link; after the first slash, you choose which DB you want to use.
Examples
// DB NAME youinsertinheredbname
var link = "mongodb+srv://<user>:<password>#quizzard-dp0b2.mongodb.net/youinsertinheredbname?retryWrites=true&w=majority";
// DB NAME stackoverflow
var link = "mongodb+srv://<user>:<password>#quizzard-dp0b2.mongodb.net/stackoverflow?retryWrites=true&w=majority";
I'm facing a Mongoose's strange behaviour.
Let's analyse this simple stupid code.
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/sodatest', {
useMongoClient: true
});
var db = mongoose.connection;
var OriginalSchema = mongoose.Schema({
addedd: Date,
endPoint: Object,
inserted: Number,
total: Number
});
var OtherTestSchema = mongoose.Schema({
what: String,
modified_at: Date
});
var EndPointInTheDb = mongoose.model('aaa', OriginalSchema);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("we are connected!");
});
EndPointInTheDb.find({}, (err: String, exit: any) => {
console.log("Errore : " + err)
console.log(exit)
});
It fails and return
we are connected!
*********************
Error : null
[]
*********************
It fails because the collection "aaa" has 15 elements.
If I change the db "sodatest" with any other ( except for another one with a lowercase name ) and 'aaa' with another collection name, it does't care if I use the correct case, it returns a correct result.
we are connected!
*********************
Error : null
[ { _id: 59f76203592b426a16b8b32f,
modified_at: 2017-10-30T17:31:47.622Z,
last_position: 5,
what: 'CONTATOREGEOKEY',
__v: 0 } ]
*********************
(it works also with multiple elements)
I've tried to copy the db in another one,
db.copyDatabase("sodatest","Prova14")
with a name with at least an uppercase char (Prova14), but again no result.
I've checked for hours if I've misspelled a name, but really, I'm sure of it.
I can't understand why it works with any other db ( 14 others with heterogeneous schema) also if I use a schema ("OtherTestSchema" ) that does not match with the collection real schema.... but not with sodatest.
Any Idea ?
Mongoose automatically adds an 's' at the end of the collection name if one is not provided. For Example:
// This will create a collection called 'aaas' since 'aaa' is passed as the
// model name
var EndPointInTheDb = mongoose.model('aaa', OriginalSchema);
// This is how you declare your collection name with a custom collection 'aaa'
var CorrectEndPointInTheDbToCollection = mongoose.model('aaa', OriginalSchema, 'aaa');
CorrectEndPointInTheDbToCollection.find({}, function(err, docs){
console.log(docs)
})
So the initializer for mongoose is mongoose.model('model name', Schema, 'optional collection name'). Highly recommend you pass in the collection name so you know it's pointing to the right collection
I have the following code based on the quickstart from Mongoose Docs.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
var kittySchema = mongoose.Schema({
name: String
});
var kitten = mongoose.model('kitten', kittySchema);
kitten.find(function(err, kittens) {
if(err)
return console.error(err);
console.log(kittens[0].name);
});
});
What I want to do is log the name from each kitten in the DB.
The example above returns the name of the first kitten in the array with kittens[0].name but when I try to do the following:
for(var i in kittens){
console.log(kittens[i].name);
}
it returns undefined for each item in the DB.
I have tried converting the i variable to a number because it comes as a string but no luck.
How can I retrieve the property name of every item that comes with .find()?
Why dont you try this:
for(var i=0; i<kittens.length; i++){
console.log(kittens[i].name);
}
since, find returns an array i.e. kittens here, kittens.length will give the length of the kittens array.
Hope it helps.
I cant create my database 'sms-dev' in mongodb after starting the server but in my console it was printing connected to mongo successfully.I kept my db module inside models folder as db.js and export that module in another file(config.js) inside models folder
Here is the code in db.js file
var db = {
// Connects to mongoDB
connect: function(url, options) {
mongoose.connect(url, options);
mongoose.connection.on('open', function(){
console.log("Connected to mongo successfully");
});
mongoose.connection.on('disconnect', function(){
console.log("Mongo disconnected");
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});
}
}
module.exports = db;
and my config.js file is
exports.database = {
url: 'mongodb://127.0.0.1:27017/sms-dev',
options: {
db: { native_parser: true,safe:true },
server: { poolSize: 10 }
}
}
I connected this db in server.js as
var dbcon = process.env.MONGOLAB_URI || config.database.url;
db.connect(dbcon, config.database.options);
This line:
As soon as you create a record with that connection
From this answer.
Did it for me. In my case I had to manually:
Create the database
Create a collection
Create a record in the collection
And then everything was good again.
You should keep your db connection very simple as you are using mongoose.
mongoose.connect should only be called once. That will create the default connection pool for your application.
//db.js
// Bring Mongoose into the app
var mongoose = require( 'mongoose' );
// Create the database connection
mongoose.connect('mongodb://127.0.0.1:27017/sms-dev');
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + 'mongodb://127.0.0.1:27017/sms-dev');
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});
You can then easily use the db connection by require mongoose in your files.
//users.js
var mongoose = require( 'mongoose' ),
Users = mongoose.model('users');
It seems that my mongodb was not locked properly so i remove the mongodb.lock file and run with -repair option
Once you ll save data in the database
,You can see the Database by running command
show dbs
const mongoose=require("mongoose")
mongoose.connect('mongodb://localhost:27017/username_db');
var db=mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connected successfully")
});
const Schema=mongoose.Schema;
const myschema=new Schema({
name:String,
},{
timestamps:true
});
var model=mongoose.model('myname',myschema);
var data=new myname({
name: 'xyz',
})
data.save((err)=>{
res.send("Error in saving to database");
})
Once you ll save data in the database
,You can see the Database by running command
show dbs
const mongoose=require("mongoose")
mongoose.connect('mongodb://localhost:27017/username_db');
var db=mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connected successfully")
});
const Schema=mongoose.Schema;
const myschema=new Schema({
name:String,
},{
timestamps:true
});
var model=mongoose.model('myname',myschema);
var data=new myname({
name: 'xyz',
})
data.save((err)=>{
res.send("Error in saving to database");
})
This is quite old Post, to which I am updating using latest packages - This solution will fix this mongo db connection issue on following version of env.
Node version - 11.5.0 (node -v)
NPM. - 6.4.1(npm -v)
Typescript. - 3.8.3(tsc -v)
Mongodb. - 5.9.15 (package.json)
Following are the steps need to take care in order to fix this -
1. First of all verify all changes in .ts file will be reflecting changes in corresponding .js file. As it was issue with my code it was not being updated.
Run following command and verify .js file
tsc --build tsconfig.json
If js file is not being updated simply delete.js file and run above command. It's pretty simple fix but some time we overlook for it.
Since it's typescript code. So need to copy past below code for verification.
Import * as m from 'mongoose';
export class UserControl {
RegisterUser(){
Const uri = "mongodb://127.0.0.1:27017/User";
m.connect(uri,
{useNewUrlPaerser:true,
useUnifiedTopology:true,
useFindAndModify:true,
useCreateIndex:true });
Let db = m.connection;
Db.once("open",async() =>.
{console.log(connected)});
Db.once("error",async() =>
{console.log(error)});
Const userSchema = new m.schema({
FirstName:string,
Last name:string
});
Const User = m.model('users', userSchema);
Const user = new User({
FName:Andy,
LName:Pat });
Const result = await user.save();
Console.log(result);
}
Run your solution by npm start.
Verify if db collection created?
If not.
First create db with name as "User" in mongodb
Using mongo db compass.
And than try. Still not able to see the collection.
Now need to start two separate console terminal.
go to folder and executive mongo
c:\program file\MongoDb\server\4.2\bin> mongo.exe
on another terminal type mongod ,
it will start your mongo Damon.
Now try. Since this above step will stable connection and show 1 connection active.
Hope this update help.
If you are using Mongoose or MongoClient to connect the mongodb database you will see the database created after you save the first document to the database.
e.g.: the below code will only show connection was successful but it does not create the database 'mydb'
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb')
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
The databse 'mydb' is created only when you save first document record.
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean
});
const Course = mongoose.model('Course', courseSchema);
async function createCourse(){
const course = new Course({
name: 'Some Course',
author: 'My Name',
tags: ['JavaScript', 'backend'],
isPublished: true
});
const result = await course.save();
console.log(result);
}
createCourse();
This is a duplicate of:
Mongo db that does not exist but shows up in connection
If you insert data your database will be created.