I'm trying to connect to a mongodb container using mongoose. This is my docker-compose:
version: "3"
networks:
mongonet:
services:
mongodatabase:
image: mongo
container_name: mongodatabase
ports:
- 27017:27017
environment:
- MONGO_INITDB_DATABASE=admin
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
networks:
- mongonet
mongojs:
depends_on:
mongodatabase:
condition: service_started
container_name: mongojs
build: .
ports:
- 8080:8080
environment:
- MONGO_URI=mongodb://mongodatabase:27017/test
networks:
- mongonet
Containers start and work ok, but problems appear when using mongoose:
const mongoose = requrie('mongoose')
const {MONGO_URI} = require('./../config/env')
exports.__mongo_ini = async function () {
const connectOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try {
await mongoose.connect(MONGO_URI, connectOptions)
console.info(`===> Connected to database ${MONGO_URI}`)
}
catch(err) {
console.warn(`===> Couldn't connect: ${err}`)
}
}
When using the env URI mongodb://mongodatabase:27017/test It says connected. But then If I try to find a model:
await models.Star.find().catch(r => r)
I get the error:
MongoServerError: command find requires authentication
at Connection.onMessage (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:203:30)
at MessageStream.<anonymous> (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:63:60)
....
ok: 0,
code: 13,
codeName: 'Unauthorized',
[Symbol(errorLabels)]: Set(0) {}
}
My model:
const starSchema = new mongoose.Schema({
starName: {
type: String,
unique: true,
required: true
},
image: {
type: String
},
designation: {
type: String
},
constelation: {
type: String
},
named: {
type: Date
},
timeStamp: {
type: Date,
default: Date.now()
}
})
const Star = mongoose.model('Star',starSchema)
module.exports = Star
Tried to add a mongo entrypoint volume in my docker compose:
volumes:
- ./mongo-entrypoint/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
Mongo-init.js:
db.getSiblingDB('admin').createUser({
user: 'testuser',
pwd: 'testpass',
roles: [
{
role: 'readWrite',
db: 'test'
}
]
})
db.getSiblingDB('test').createCollection('collection_test');
So I try to connect changing the mongo uri to use user and password:
MONGO_URI=mongodb://testuser:testpass#mongodatabase:27017/test
But It says authentication failed when trying to connect to the mongo uri and the mongo entrypoint doesn't seem to run:
Couldn't connect: MongoServerError: Authentication failed.
I've tried so many things and none of them work. All help is appreciated.
Try this code in node js
database.js
require("dotenv").config();
const mongoose = require("mongoose");
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connection SUCCESS");
} catch (error) {
console.error("MongoDB connection FAIL");
}
};
module.exports = connectDB;
.env
MONGO_URI=your_mongodb_url
Create a models file
models.js
const mongoose = require("mongoose");
const CategorysSchema = new mongoose.Schema({
description: {
type: String,
lowercase: true,
},
name: {
type: String,
lowercase: true,
},
publishedAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("categorys_collection", CategorysSchema);
Find Models
const Category_Model = require("./models");
app.get("/", async (req, res) => {
try {
const Category = await Category_Model.find();
res.json(Category);
} catch (error) {
res.status(500).json({ message: error.message, status: "error" });
}
});
Related
Here I created a project to store employee information, in this project DB also successfully connected, but when I tried to retrieve or create a new record, it shows error like this,
I already changed the mongo network setting also,
MongooseError: Operation users.insertOne() buffering timed out after 10000ms
at Timeout.
server.js
const express = require("express");
const mongoose = require("mongoose");
const Router = require("./routes");
const cors = require('cors');
const { error } = require("jquery");
const app = express();
app.use(express.json());
mongoose.set('strictQuery', false);
mongoose.connect('mongodb+srv://admin:admin1234#hhap-db.n8zxs62.mongodb.net/test',
{ useNewUrlParser: true, useFindAndModify: true, useUnifiedTopology: true },
function CheckDb(){
if(error){
console.log("Error");
}
else{
console.log("DB Connected");
}
}
);
app.use(Router);
app.use(cors());
app.listen(3000, () => {
console.log("Server is running at port 3000");
});
router.js
const express = require("express");
const userModel = require("./model/userModel");
const app = express();
app.post("/user/create", async (request, response) => {
const user = new userModel(request.body);
try {
await user.save();
response.send(user);
} catch (error) {
response.status(500).send(error);
console.log(error);
}
});
app.get("/user/getAll", async (request,response) => {
const user = await userModel.find({});
console.log(user);
try {
response.send(user);
} catch (error) {
response.status(500).send(error);
console.log(error);
}
});
module.exports = app;
userModel.js
const mongoose = require("mongoose");
const user = new mongoose.Schema({
fName: { type: String, required: true, },
lName: { type: String, required: true, },
address: { type: String, required: false, },
email: { type: String, required: true, },
mobileNumber: { type: Number, default: 0, },
password: { type: String, required: true, },
isActive: { type: Boolean, required: true, },
userType: { type: String, required: true, },
});
const User = mongoose.model("user", user);
module.exports = User;
Issue in mongoose.connect
Try this:
mongoose
.connect("mongodb+srv://admin:admin1234#hhap-db.n8zxs62.mongodb.net/test", {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
useCreateIndex: true,
keepAlive: true
})
.then(
async() => {
console.log("database connected")
},
(err) => {
console.log(err, "Error")
}
)
i got this error about 5 seconds after clicking send in postman:
{
"message": {}
}
Where the error happens:
router.post('/', async (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({message: err}); // here
}
});
I got the connected to DB in the console.log (mongo is run by docker-compose)
mongodb:
image: mongo
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: admin
MONGO_INITDB_DATABASE: test_db
ports:
- 27017:27017
DB_CONNECTION=mongodb://admin:admin#mongodb:27017/test_db
mongoose.connect(
process.env.DB_CONNECTION,
{
useNewUrlParser: true,
useUnifiedTopology: true
},
() => console.log('connected to DB!!!') // call back
);
Schema for post:
const mongoose = require('mongoose');
// describe how the data looks
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('Posts', PostSchema)
However, when I update the DB_connection to :
DB_CONNECTION=mongodb://admin:admin#mongodb:27017 (removing the /test_db)
the problem is gone and i and perfectly adding document to mongodb (but not in the test_db)
anyone knows where the problem is?
Thanks a lot!!
You can always use a callbacks:
post.save(function(err, obj) {
if (err)
res.send(err);
res.json({ message: 'created!', data: obj });
});
I am trying to integrate mongoose and apollo with Next.js
I wrote this wrapper around apollo server:
import mongoose from "mongoose"
const {logger} = require("../middleware/logger");
const connect = async () => {
logger.info("Connecting to DB...");
await mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(() => logger.info(`Mongo running at ${process.env.MONGO_URI}`))
.catch(err => logger.error(err));
}
const connectDB = (handler) => async (req, res) => {
if (mongoose.connections[0].readyState !== 1) {
await connect();
}
return handler(req, res);
}
const db = mongoose.connection;
db.once('ready', () => logger.info(`Connected to mongo on ${process.env.MONGO_URI}`));
export default connectDB;
In this model in separate file:
const mongoose = require('mongoose');
const {Schema} = mongoose;
const CustomerSchema = new Schema({
name: {
type: String,
required: [true, 'Customer name is required'],
unique: true,
trim: true,
},
createdAt: {
type: Date,
default: Date.now
}
}, {
toJSON: {
transform: function (doc, ret) {
ret._id = ret._id.toString();
delete ret.__v
}
}
});
module.exports = mongoose.model('Customer', CustomerSchema);
My apollo server looks like this now:
import {ApolloServer, gql} from "apollo-server-micro";
import connectDB from "../../middleware/db-middleware";
const _Customer = require("../../db/models/Customer");
const typeDefs = gql`
type Customer {
id: ID!
name: String!
createdAt: String
}
type Query {
hello: String!
}
type NewCustomerResponse {
success: Boolean!
message: String
}
type Mutation {
addCustomer(name: String!): NewCustomerResponse!
}
`;
const resolvers = {
Mutation: {
addCustomer: async (parent, {name}, context, info) => {
await _Customer.create({name});
return {success: true, message: "Sample message"};
}
}
};
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: () => ({}),
});
export default connectDB(apolloServer.createHandler({path: "/api/gql"}));
First run works ok, but when I modify anything, and next.js auto-recompiles source files, it throws this error:
OverwriteModelError: Cannot overwrite `Customer` model once compiled.
Does anyone knows what am I doing wrong and how to resolve this issue?
i try to change my Db from mongodb to mysql, i use sequelize instead of mongoose, and i got this error, i created the User.js model with sequelize format, but something wrong and i don't know why
const User = sequelize.define('users', {
^
TypeError: Cannot read property 'define' of undefined"
Here is my code:
server.js
const Sequelize = require('sequelize');
// DB Config
const db = require('./config/keys');
// Connect to MySql
const sequelize = new Sequelize(db.database, db.user, db.password, {
host: db.host,
dialect: 'mysql',
port: db.port
});
// Test the connection
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
const serverDB = {};
serverDB.sequelize = sequelize;
serverDB.Sequelize = Sequelize;
module.exports = serverDB;
Users.js
const serverDB = require('../server');
const sequelize = serverDB.sequelize;
const Sequelize = serverDB.Sequelize;
const User = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
avatar: {
type: STRING
},
date: {
type: Sequelize.DATE,
defaudefaultValue: Sequelize.NOW
}
});
sequelize.models.modelName
// sequelize.sync()
// .then(() => {
// console.log('User db and user table have been created')
// });
module.exports = User;
You should add
const Sequelize = require('sequelize');
in your client too.
And only export and use the lowercase sequelize.
And ensure relative path of server.js is good.
I am building a node app and want to use waterline and mysql without sails. I cannot get the adapter to work. The exact error I get with the code from below is:
C:\node\mlb\node_modules\waterline\lib\waterline\core\index.js:70
var schemaAttributes = this.waterline.schema[this.identity].attributes;
TypeError: Cannot read property 'undefined' of undefined
Here is my code:
var Waterline = require('waterline');
var mysql = require('sails-mysql');
mysql.config = {
host: 'localhost',
database: 'mlb',
port: '3306',
username: 'admin',
password: 'xxxxxxxx'
}
var Batter = Waterline.Collection.extend({
adapter: 'mysql',
attributes: {
name: {
type: 'string',
required: true
}
}
});
new Batter({ tableName: 'batters', adapters: { mysql: mysql }}, function (err, Model) {
Model.findAll().exec(function(err, batters) {
// Now we have an array of users
});
});