GithubHelp home page GithubHelp logo

mongo-provider's Introduction

Mongo

Mongo Provider

Swift CircleCI Slack Status

โฌ‡ Install the MongoDB server

OS X

For more instructions, check out https://docs.mongodb.com/master/administration/install-community/.

brew install mongodb

Linux

sudo apt-get update
sudo apt-get install mongodb

Run the server

mongod

๐Ÿ“ฆ Add Provider

Now to use Mongo in your Vapor project.

Package

Add the package to your Package.swift.

.Package(url: "https://github.com/vapor/mongo-provider.git", majorVersion: 2)

Droplet

Add the provider to your Droplet.

import Vapor
import MongoProvider

let drop = Droplet()
try drop.addProvider(MongoProvider.Provider.self)

And configure Fluent to use MongoDB by changing the key "driver" to be "mongo" inside `Config/fluent.json

Config

Then add a mongo.json to your Config folder. You can add it in the root or keep it out of git in the secrets folder.

Config/
  - mongo.json
    secrets/
      - mongo.json

The secrets folder is under the .gitignore and shouldn't be committed.

Here's an example secrets/mongo.json

{
  "url": "mongodb://<db-user>:<db-password>@<host>:<port>/<database>"
}

Note: port and host are optional.

Manual

You can also manually configure the provider in code. This will bypass the configuration files.

import Vapor
import MongoProvider

let drop = Droplet()

let mongo = try MongoProvider.Provider(database: ..., user: ..., password: ...)
drop.addProvider(mongo)

๐Ÿ“– Documentation

Visit the Vapor web framework's documentation for more instructions on how to use this package.

๐Ÿ’ง Community

Join the welcoming community of fellow Vapor developers in slack.

๐Ÿ”ง Compatibility

This package has been tested on macOS and Ubuntu.

mongo-provider's People

Contributors

api-live avatar honghaoz avatar islandjoe avatar joannis avatar tanner0101 avatar vzsg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongo-provider's Issues

Referencing other object id

This is more of a question with a potential of becoming a feature request.

This code:

var post = Post(userId: Node(user.id!, content: content)
try post.save()

Produces this:

1

This code:

var post = Post(userId: Node(["$oid" : user.id!]), content: content)
try post.save()

Produces this:

2

But how do I achieve this?

proper

user and password need escaping when building server URL

any / or @ chars in password will make the provider init to crash, like this one:

let mongo = try VaporMongo.Provider(database: "mydb", user: "joeshmo", password: "password@")

the following init changes fixed my issue:

public init(database: String, user: String, password: String, host: String, port: Int) throws {
        let escapedUser = user.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        let escapedPassword = password.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        let server = try Server("mongodb://\(escapedUser):\(escapedPassword)@\(host):\(port)", automatically: true)
        self.database = server[database]
}

mongokitten is also missing the unescaping on the other side but that is another issue I guess...

I can make a pull request if that helps.

`model.save()` triggers `Unsupported Node type, only array is supported.`

I'm using mongo as my database provider.

When I modify a model and save() it, Unsupported Node type, only array is supported. is logged into the console. But this model can save successfully anyway.

Following is my code:

main.swift

import Vapor
import Foundation
import VaporMongo
import HTTP

let drop = Droplet(
    preparations: [
        User.self,
        Post.self,
    ],
    providers: [
        VaporMongo.Provider.self
    ]
)

// MARK: - Route
// Users
drop.group("/users", closure: UserController().route)

drop.run()

UserController.swift

import Vapor
import HTTP
import Routing

final class UserController: ControllerRouting {
    func route(routeGroup: RouteGroup<Responder, Droplet>) {
        routeGroup.get(handler: showUsers)
        routeGroup.get("*") { request in
            return "404"
        }
    }
}

extension UserController {
    func showUsers(_ req: Request) throws -> ResponseRepresentable {
        var users = try User.all()

        if var foundUser = users.first {
            foundUser.name = "Honghao"
            try foundUser.save()
        } else {
            print("No any User found")
            var newUser = User(name: "Honghao")
            try newUser.save()
            print("Created: \(newUser.id)")
            users = [newUser]
        }

        let usersString = users.map({ $0.name }).joined(separator: ", ")

        return try drop.view.make("users", [
            "user": Node.string(usersString)
            ]
        )
    }
}

User.swift

import Vapor
import Fluent
import Foundation

final class User: Model {
    var name: String

    // MARK: - Entity
    var id: Node?
    var exists: Bool = false

    init(name: String) {
        self.id = UUID().uuidString.makeNode()
        self.name = name
    }

    init(node: Node, in context: Context) throws {
        id = try node.extract("_id")
        name = try node.extract("name")
    }

    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "_id": id,
            "name": name
        ])
    }
}

// MARK: - Preparation
extension User {
    static func prepare(_ database: Database) throws {
        // Mongo doesn't need to prepare
    }

    static func revert(_ database: Database) throws { }
}

MongoProvider error

How can I setup correctly to not occurs this error:

fatal error: Error raised at top level: Socket failed with code 61 ("Connection refused") [connectFailed]: 
file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.58.6/src/swift/stdlib/public/core/ErrorType.swift, line 184

Crash when deployed on Linux (Ubuntu, AWS, Heroku)

I am experiencing a strange crash with when working with Vapor+Mongo. I have an app deployed on Heroku with just one route that does

do {
    let objects = try MyEntity.all()
    return "done"
} catch (let error) {
    throw Abort.custom(status: .badRequest, message: error.localizedDescription)
}

Notice, that after fetching all entities, they are discarded.

MyEntity conforms to Model and only thing that it extracts is the id.

This works fine when running from the Xcode (I have hardcoded a connection URL to mLab DB in main.swift, so that I have least moving parts). When I deploy it to Heroku, the first request succeeds and after that the server crashes (without any logs or stack trace) and I have to restart it.

The mongo collection that I am fetching contains only a single object that has only the _id and a date:

{
    "_id" : ObjectId("58223184aa892cc027c91456"),
    "date" : ISODate("2016-10-05T16:54:36.705Z")
}

Now, the interesting part is that if I remove the date then all requests succeed on both Xcode and Heroku, but if I put the date back, it still works fine from Xcode, but starting from second/third request onwards, it starts crashing on Heroku.

Breaks CryptoSwift

When installing the provider, the cryptoswift framework breaks unless it is put into editable mode using the following line:

swift package edit CryptoSwift --revision develop

These needs to be added to the installation instructions

[QUESTION] Vapor 3

Hi guys! Thanks for this first of all.

I was wondering if I can use this provider with Vapor 3 like I'm already doing in Vapor 2.

Any clue?

Adding provider to Vapor project throws error

Hello,

I'm using Vapor 2 with MongoProvider. But the code below compiles but throws an error and prints the message inside the catch block.

do {
    try config.addProvider(MongoProvider.Provider.self)
} catch {
  print("Adding provider failed")
}

I have fluent.json file and it has the only uuid type declaration.

{
   "idType": "uuid"
}

Lastly, I have mongo.json file under Config folder.

{
  "host": "127.0.0.1",
  "database": "test_db",
  "port": "27017",
  "user": "admin",
  "password": "password"
}

Am I missing something or is there a bug?

"user" and "password" are (unnecessarily) required

The Provider expects "user" and "password" to be present in the config file, but Mongodb itself doesn't require this - you can have a database without username and password set (for development, mainly).

Key url in Config/mongo.json

mongo.json

{
  "user": "root",
  "password": "",
  "database": "dwblog",
  "port": "27017",
  "host": "127.0.0.1"
}

then run
error

fatal error: Error raised at top level: Configuration error: Key url in Config/mongo.json of type String required.: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift, line 188

"id" not populated on first save

I have made a model and saved it to a Mongo DB. My model creates "var id: Node?" and init to "self.id = nil". However, when the record is saved I notice Mongo creates a different "_id" with values like this "ObjectId("31943c580047b1f729e088f5")". The "id" field is left null as you can see here:

screen shot 2016-11-28 at 4 16 04 pm

However, if I do the same thing but save the model twice then it seems to populate the "id" field as you can see here:

screen shot 2016-11-28 at 4 47 27 pm

I believe this should have been done on the first save, but if you have multiple documents, it will arbitrarily update the id of the first document it finds (i.e., not necessarily the correct one)

Query logging is unsupported

i got this "Query logging is unsupported" when i tried to run the server

here is my configuration in main.swift :

import App
import MongoProvider

let config = try Config()
try config.setup()
try config.addProvider(MongoProvider.Provider.self)
let drop = try Droplet(config)
try drop.setup()

drop.get("version") { request in
    if let db = drop.database?.driver as? MongoDriver {
        let version = try db.raw("SELECT version()")
        return JSON(node: version)
    } else {
        return "No db connection"
    }
}

try drop.run()

also, i've added value "mongo" in fluent.json

Mongodb Fetch Error

I use mongodb code like this:

var user = User(name: "Vapor")
    user.id = Node(42)
    do {
        try user.save()
    } catch let e {
        print(e)
    }
    let u = try User.find(42)
    print("fetch \(u)") // is nil

The u is nil, the fetch query sql is

select("users", [(User) _id equals number(42)], [], [], Optional(Fluent.Limit(count: 1, offset: 0)))

the '_id' is mongodb default key๏ผŒnot my 'id' key of 'User' Model.
Is this a Bug?

Is Readme uptodate?

Readme says after adding package, to follow code

import Vapor
import VaporMongo

let drop = Droplet()
try drop.addProvider(VaporMongo.Provider.self)

But its giving error for me. Saying that no such module 'VaporMongo'
My code that works is

import MongoProvider

let config = try Config()
try config.setup()

try config.addProvider(MongoProvider.Provider.self)

let drop = try Droplet(config)

Is anything wrong with my steps or should the read to be updated?

Illegal instruction error

Running swift build on a boiler-plate vapor project returns the following output:

Cloning https://github.com/vapor/mongo-provider.git
HEAD is now at 55b961b Merge pull request #3 from honghaoz/master
Resolved version: 1.1.0
Cloning https://github.com/vapor/mongo-driver.git
HEAD is now at e26a3f1 Merge pull request #30 from vapor/fluent-1.3
Resolved version: 1.0.9
Cloning https://github.com/OpenKitten/MongoKitten.git
Illegal instruction: 4

Package.swift includes the following as dependencies:

    .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 3),
    .Package(url: "https://github.com/vapor/mongo-provider.git", majorVersion: 1, minor: 1)

UPDATE:
I was able to work around this issue by using Swift 3.0.2 SPM. So I guess it's something related to SPM.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.