so I'm currently trying to develop a mmorpg from scratch and got up to trying to save users from my client side (I'm using game maker studio). Im using robomongo as my Mongodb management tool.
My client connects just fine to my server and im able to take in a username and password but nothing is being saved to the database i created. Here is my user.js file:
var mongoose=require('mongoose');
var userSchema=new mongoose.Schema({
username: {type: String, unique:true},
password: String,
sprite:String,
current_room: String,
pos_x:Number,
pos_y:Number
});
userSchema.statics.register=function(username,password,cb){
var new_user=new User({
username: username,
password: password,
sprite: "spr_Hero",
current_room:maps[config.starting_zone].room,
pos_x:maps[config.starting_zone].start_x,
pos_y:maps[config.starting_zone].start_y,
});
//save user to database
new_user.save(function(err){
if(!err){
cb(true)
}else{
cb(false);
}
});
};
userSchema.statics.login=function(username,password,cb){
//findOne searched db - mongodb specific method
//searches db using json objects (cant do that in other sql/mysql)
User.findOne({username:username},function(err,user){
if(!err && user){
if(user.password==password){
cb(true,user);
}else{
cb(false,null);
}
}else{
//error||user doesnt exist
cb(false,null);
}
})
};
//export into gloabl space of our application
module.exports=User=gamedb.model('User',userSchema);
and here is my mongodb.js file. I configured the database location in my config.js. Im just using my local ip. Any help on fixing this would be great thanks!
var mongoose=require('mongoose');
mongoose.Promise=global.Promise;
module.exports=gamedb=mongoose.createConnection(config.database);
Seems like you are using MongoDB 3.4 which is not supported by Robomongo currently, but it will be soon. You can follow this ticket for updates: https://github.com/Studio3T/robomongo/issues/1250
Note: I am one of the contributors of Robomongo.
Related
Before you close this question, I have read several forums that have the same question as I have but my issue is way different. Even when Im not trying to do anything, even save a model, it still gives me an error of:
cannot overwrite "mongoose" model once compiled
I have a feeling there is something wrong with my schemas because when it was still simpler, it worked fine but as I tried to make it more complex it started to give me that error. Here is my mongoose code:
import mongoose from 'mongoose'
const flashcardItemSchema = new mongoose.Schema({
term: {
type:String,
required: true,
min:1
},
description: {
type:String,
required:true,
min:1
}
});
const FlashcardItem = mongoose.model("flashcardItem", flashcardItemSchema);
const flashcardSetSchema = new mongoose.Schema({
title: {
type: String,
min: 1,
},
flashcards:[flashcardItemSchema],
})
const FlashcardSet = mongoose.model('flashcardSet', flashcardSetSchema )
export {FlashcardItem, FlashcardSet}
I connect to my database when the server runs, so it doesn't disconnect from time to time.
UPDATE
I realized that I'm using nextjs builtin api, meaning the api directory is inside the page directory. I only get the error once the pages get recompiled.
So it turns out that the error came from nextjs trying to remake the model every render. There is an answer here: Mongoose/NextJS - Model is not defined / Cannot overwrite model once compiled
but I thought the code was too long and all that fixed mine was just a single line. When trying to save a model in nextjs, it should be written like this:
const modelName = mongoose.models.modelName || mongoose.model('modelName', flashcardSetSchema )
I am working on trying to connect a Node/Express server to an existing MongoDB Database/Collection. I have already successfully connected to the database. However, I am having a tremendously difficult time setting up my models/schema to query.
The MongoDB is MongoDB Atlas and has one collection with over 800,000 documents. The name of the single collection is "delitosCollection".
I have tried the following to with no success:
var CrimeData = mongoose.model('DelitosCollection', new Schema({}),'delitosCollection');
mongoose.connection.on('open', function(ref){
console.log("connected to the mongo server");
CrimeData.find({}, (err,results) => {
if(err){
console.log("ERROR")
throw err
}
console.log("results: ", results.length)
} )
});
I know the connection is working as I am receiving the console.log with no errors. However, results.length is returning 0 when it should be over 800,000. Have spent way too many hours on this.
Create an empty schema for each collection you want to use
and then create a model to be used in your project
the model take 3 parameter
1)name of the model
2)schema name
3)collection name ( from mongodb atlas)
like that
const mongoose = require('mongoose');
mongoose.connect('mongodb uri')
const userSchema = new mongoose.Schema({});
const User = mongoose.model('User', userSchema, 'user');
then you can use the model normally
User.find({})
connection to mongo db
// Connect to mongoDB
mongoose.connect('mongodb://localhost/[yourDbName]',{useNewUrlParser:true})
.then(function(){
console.log('mongoDB connected');
})
.catch(function(){
console.log('Error :');
})
after that you will have to create your schema and then only you can query the database
create your schema like this
// Crimes Schema
const CrimeDetailsSchema= new Schema({
first_name: {
type: String,
required: true
},
last_name: {
type: String,
required: true
},
email: {
type: String,
required: true
}
});
const Profile = module.exports = mongoose.model('delitosCollection', CrimeDetailsSchema, 'delitosCollection');
after that create your queries
you can get an idea about that in mongoose documentation here
You can refer to the answer given below, just pass an empty object in schema
like db.model('users', new Schema({}))
We have migrate our database to MongoLab via Heroku but now our cloudcode doesn't work anymore.
After looking the code, it seems all the features of Geopoint doesn't work with MongoDB.
Here is our code:
var userGeoPoint = new Parse.GeoPoint(latitude, longitude);
var query = new Parse.Query("User");
query.near("location", userGeoPoint);
query.limit(10);
query.find({
success: function(placesObjects) {
console.log("yes");
},
error:function(status) {
console.log(status);
}
});
And here is the answer:
Result: {"code":1,"message":"internal error"}
Any help will save my life...
Thanks!
I ran into the same issue originally but I fixed it with set failIndexKeyTooLong=false. Sandbox from mLab doesn't support this feature.
MongoInternals.RemoteCollectionDriver("mongodb://#{server.ip}:#{server.port}/#{server.dbName}")
If I call multiple remote MongoDB methods and if there are collecitons with the same names, Meteor throws the error something like this, "collectionName/insert is already exist..."
I think Meteor creates each collection's methods internally so that control each collection, but I need to control several MongoDB at a time with some reasons.
How can I avoid this situation?
In addition,
I realize I can use Npm Mongo driver directly like this without any NPM package involving.
var MongoClient = MongoInternals.NpmModules.mongodb.module.MongoClient;
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
console.log("Connected correctly to server");
try {
var collection = db.collection('documents');
collection.find({}).toArray(function(err, docs){
console.log(err);
console.log(docs);
});
}
catch(err) {
console.log(err);
}
db.close();
});
But this still forces me to control each DB with the Node.js callback style.
Is there any idea to avoid this?
I have been checking this issue, and I found a way to do it.
The solutions that I had seen to connect several databases where:
storageServerDriver = new MongoInternals.RemoteCollectionDriver("mongodb://ip:port/dbName")
#Collection = new Mongo.Collection("collection", { _driver: storageServerDriver })
But as you mentioned before, with two collections with same name, an error was thrown (internally Meteor identifies the collections by their name, so it tries to override the structure of the collection already created).
Anyway, to fix this, you can use the following hack:
storageServerDriver = new MongoInternals.RemoteCollectionDriver("mongodb://ip:port/dbName")
#CollectionTwo = storageServerDriver.open('collection')
I am using mongoose and setting up schema for users as follows:
var users=new mongoose.Schema({
username:String,
password:String,
type:String
});
var User=mongoose.model('user',users);
Now i need this to have a initial row with values as admin,admin,admin
How to do this?
I am using express server to verify a user like this
app.post("/verifyLogin",function(request,response){
var usr=request.body.username;
var pass=request.body.password;
//VERIFICATION FROM DATABASE CODE GOES HERE
});
P.S I am new to mongodb/document-based data storage. Until now i used to work with phpmyadmin and insert data directly from the interface provided.
WHAT I TRIED:
i made a temp post handler like this
app.post("/initialize/database",function(request,response){
var user=new userModel({username:'admin',password:'password', type:'admin'});
user.save(function(err){
if(!err){return console.log('created')}else{console.log(err)}
return response.send(user);
});
})
and then in the console did this:
jQuery.post('/initialize/database',function(data){console.log(data)})
Don't know whether this is the best approach or not :(
I find it easiest to enter initialization data from the terminal.
$ mongo
> use database-name
> db.users.insert({ username: 'admin', password: 'admin', type: 'admin' })
That would work for simply getting things going, but I forbid you to store plain-text passwords in the database when in production. To implement hashing and to use node instead of the terminal you could create a route for creating a new user instead. Something like:
app.post("/signup",function(request,response){
var usr = request.body.username,
pass = request.body.password;
somePasswordHashingAlgoritm(pass, function (hashedPassword) {
User.insert({
username: usr,
password: hashedPassword,
type: 'admin'
});
});
});
Even better would be to implement a pre-save hook in mongoose, but that's the subject for another topic. If you don't want others to sign up to your site, just remove that code when you've created yourself.