GithubHelp home page GithubHelp logo

denodrivers / mongo Goto Github PK

View Code? Open in Web Editor NEW
509.0 16.0 96.0 615 KB

๐Ÿƒ MongoDB driver for Deno ๐Ÿฆ•

Home Page: https://deno.land/x/mongo

License: MIT License

TypeScript 100.00%
mongodb deno driver database deno-deploy typescript

mongo's Introduction

deno_mongo

deno_mongo is a MongoDB database driver developed for Deno. supports Deno Deploy as well.

ATTENTION

Deno have added the support for npm modules. so you can also use npm:mongodb driver from now.
Each of these two drivers has its own advantages and disadvantages. you can follow this issue for more details. In short:

  • if you want to use basic MongoDB operations and you don't care about stability, this driver just works.
  • if you want most of MongoDB feature working with Deno and you don't care about the possible overheads by using node compat layer, you may try the npm:mongodb driver
  • if you are using MongoDB Atlas, using atlas_sdk can be your best option.

tag Build Status license Discord server

Links

Import

Replace LATEST_VERSION with current latest version

import {
  Bson,
  MongoClient,
} from "https://deno.land/x/mongo@LATEST_VERSION/mod.ts";

Connect

const client = new MongoClient();

// Connecting to a Local Database
await client.connect("mongodb://127.0.0.1:27017");

// Connecting to a Mongo Atlas Database
await client.connect({
  db: "<db_name>",
  tls: true,
  servers: [
    {
      host: "<db_cluster_url>",
      port: 27017,
    },
  ],
  credential: {
    username: "<username>",
    password: "<password>",
    db: "<db_name>",
    mechanism: "SCRAM-SHA-1",
  },
});

// Connect using srv url
await client.connect(
  "mongodb+srv://<username>:<password>@<db_cluster_url>/<db_name>?authMechanism=SCRAM-SHA-1",
);

Access Collection

// Defining schema interface
interface UserSchema {
  _id: ObjectId;
  username: string;
  password: string;
}

const db = client.database("test");
const users = db.collection<UserSchema>("users");

Insert

const insertId = await users.insertOne({
  username: "user1",
  password: "pass1",
});

const insertIds = await users.insertMany([
  {
    username: "user1",
    password: "pass1",
  },
  {
    username: "user2",
    password: "pass2",
  },
]);

Find

const user1 = await users.findOne({ _id: insertId });

const all_users = await users.find({ username: { $ne: null } }).toArray();

// find by ObjectId
const user1_id = await users.findOne({
  _id: new ObjectId("SOME OBJECTID STRING"),
});

Count

const count = await users.countDocuments({ username: { $ne: null } });

const estimatedCount = await users.estimatedDocumentCount({
  username: { $ne: null },
});

Aggregation

const docs = await users.aggregate([
  { $match: { username: "many" } },
  { $group: { _id: "$username", total: { $sum: 1 } } },
]).toArray();

Update

const { matchedCount, modifiedCount, upsertedId } = await users.updateOne(
  { username: { $ne: null } },
  { $set: { username: "USERNAME" } },
);

const { matchedCount, modifiedCount, upsertedId } = await users.updateMany(
  { username: { $ne: null } },
  { $set: { username: "USERNAME" } },
);

Replace

const { matchedCount, modifiedCount, upsertedId } = await users.replaceOne(
  { username: "a" },
  {
    username: "user1",
    password: "pass1",
  }, // new document
);

Delete

const deleteCount = await users.deleteOne({ _id: insertId });

const deleteCount2 = await users.deleteMany({ username: "test" });

Cursor methods

const cursor = users.find();

// Skip & Limit
cursor.skip(10).limit(10);

// iterate results
for await (const user of cursor) {
  console.log(user);
}

// or save results to array (uses more memory)
const users = await cursor.toArray();

GridFS

// Upload
const bucket = new GridFSBucket(db);
const upstream = bucket.openUploadStream("test.txt");

const writer = upstream.getWriter();
writer.write(fileContents);

await writer.close();

// Download
const file = await new Response(bucket.openDownloadStream(id)).text();

Community Resources

Tools

Examples

  • deno-deploy-mongo A simple app with Deno, MongoDB and oak deployed on Deno Deploy and MongoDB Atlas
  • deno_rest A simple oak based boilerplate for RESTful apis using deno_mongo

Contributing

Local testing with Docker

  1. docker run -d -p 27017:27017 mongo
  2. deno test -A

mongo's People

Contributors

aaron-nerox avatar andrinheusser avatar aspulse avatar bastidood avatar brunobernardino avatar buttercubz avatar c0per avatar erfanium avatar flappybug avatar fsou1 avatar hackers267 avatar hviana avatar jaspervhaastert avatar jaysok avatar lucacasonato avatar lucsoft avatar lumaghg avatar manuelaguirre avatar manyuanrong avatar mattijauhiainen avatar nicoss54 avatar radek3911 avatar rnr1 avatar robertfent avatar ronhippler avatar sekko27 avatar shubhampalriwala avatar siddeshwarnavink avatar vicky-gonsalves avatar williamhorning 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar

mongo's Issues

Find with "fields" list?

Is it possible to send a fields object to find to get back a subset of attributes?

The mongo command-line client takes a second argument like this:

db.records.find({}, {_id: 0, column1: 1, column2: 1})

Is this possible in deno_mongo?

Allow the use of generics for collections.

It would be nice to pass a generic to db.collection so that the return type of any functions that run queries such as findOne would return the right type:

interface User {
  _id: ObjectId;
  username: string;
  passwordHash: string;
}

const users = db.collection<User>("users");

users.findOne({ username: "thing" }) // -> Promise<User | void>

I can't start this plugin in 1.0.5 version of deno

Hi,
I can't start this mongo plugin with deno 1.0.5 version.

Here is the error stack

thread '<unnamed>' panicked at 'called `Option::unwrap()` on a `None` value', src/command/connect.rs:63:24
stack backtrace:
   0: backtrace::backtrace::libunwind::trace
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.44/src/backtrace/libunwind.rs:86
   1: backtrace::backtrace::trace_unsynchronized
             at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.44/src/backtrace/mod.rs:66
   2: std::sys_common::backtrace::_print_fmt
             at src/libstd/sys_common/backtrace.rs:78
   3: <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt
             at src/libstd/sys_common/backtrace.rs:59
   4: core::fmt::write
             at src/libcore/fmt/mod.rs:1063
   5: std::io::Write::write_fmt
             at src/libstd/io/mod.rs:1426
   6: std::sys_common::backtrace::_print
             at src/libstd/sys_common/backtrace.rs:62
   7: std::sys_common::backtrace::print
             at src/libstd/sys_common/backtrace.rs:49
   8: std::panicking::default_hook::{{closure}}
             at src/libstd/panicking.rs:204
   9: std::panicking::default_hook
             at src/libstd/panicking.rs:224
  10: std::panicking::rust_panic_with_hook
             at src/libstd/panicking.rs:470
  11: rust_begin_unwind
             at src/libstd/panicking.rs:378
  12: core::panicking::panic_fmt
             at src/libcore/panicking.rs:85
  13: core::panicking::panic
             at src/libcore/panicking.rs:52
  14: deno_mongo::command::connect::connect_with_uri
  15: deno_mongo::op_command
  16: <deno::ops::plugin::PluginInterface as deno_core::plugin_api::Interface>::register_op::{{closure}}
  17: deno_core::core_isolate::CoreIsolateState::dispatch_op
  18: deno_core::bindings::send
  19: <extern "C" fn(A0) .> R as rusty_v8::support::CFnFrom<F>>::mapping::c_fn
  20: _ZN2v88internal25FunctionCallbackArguments4CallENS0_15CallHandlerInfoE
  21: _ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0_11MaybeHandleINS0_6ObjectEEEPNS0_7IsolateENS0_6HandleINS0_10HeapObjectEEESA_NS8_INS0_20FunctionTemplateInfoEEENS8_IS4_EENS0_16BuiltinArgumentsE
  22: _ZN2v88internalL26Builtin_Impl_HandleApiCallENS0_16BuiltinArgumentsEPNS0_7IsolateE
  23: Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
fatal runtime error: failed to initiate panic, error 5
Aborted

API consideration: Remove await init() from public API

The await init() is needed to load the plugin, but this is an implementation detail that should not be public. It could easily be removed from the public API by calling the method internally.

This way you remove a foot-gun where users may forget to call your init method.

Delayed plugin initialisation

Hey,

First of all, thanks for all the efforts on this, I like deno_mongo very much :)

Now, here's about the issue I'm encountering. I am trying to lazy-load deno_mongo for my project denodb which handles different types of databases. The problem being that if someone only wants to use mysql, the library shouldn't load mongodb (which comes with additional command flags unstable and allow-plugin at least).

After digging in the code, I found a solution to lazy-load everything:

const { MongoClient, RELEASE_URL, init } = await import("../../unstable_deps.ts");
await init(RELEASE_URL);
const client = new MongoClient();

But obviously this is when I realised, this is already being done in mod.ts. The problem is, when lazy-loaded, the module doesn't wait on the await init(...) instruction from that file.

Uncaught Error: The plugin must be initialized before use

So far, the only solution I found was to remove that line (with init) from my local package mod.ts. Otherwise, by keeping my additional await init(...), I am getting an error saying that I am trying to initialise the same plugin twice (which makes sense).

I am therefore asking: could something be done here so that this library could be lazy-loaded when necessary? I know this might only be my problem right now, but I am sure it might be someone else's someday.

Just let me know if you could do something about this, any thought.

Thanks for your time and keep up the good work :)

Is it stable/production-ready?

I want to migrate my app from node to deno. Is deno_mongo safe for production use?
It's better to specify the status of this package somewhere.

error: TS2339 [ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'.

Cannot run the example from README.TS

import { init, MongoClient } from "https://deno.land/x/[email protected]/mod.ts";

// Initialize the plugin
await init();
const client = new MongoClient();
client.connectWithUri("mongodb://localhost:27017");
const db = client.database("testoooo");
const users = db.collection("users");

// insert
const insertId = await users.insertOne({
  username: "user1",
  password: "pass1"
});

// insertMany
const insertIds = await users.insertMany([
  {
    username: "user1",
    password: "pass1"
  },
  {
    username: "user2",
    password: "pass2"
  }
]);

Getting error:

error: TS2339 [ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'.
  return Deno.openPlugin(localPath);
              ~~~~~~~~~~
    at https://deno.land/x/[email protected]/mod.ts:64:15

It fails even with only init()

Deno Version:

deno 1.0.0
v8 8.4.300
typescript 3.9.2

Mac OS X Mojave (10.14.2)

Segmentation fault on Ubuntu 18.04 WSL 2

INFO load deno plugin "deno_mongo" from local "/mnt/d/projects/deno-crud/.deno_plugins/deno_mongo_90b8202cc9554c64927ac1e194abc3f6.so"
Segmentation fault (core dumped)

Running with command
deno run --allow-net --allow-write --allow-read --allow-plugin --unstable server.ts

File
import { init, MongoClient } from "https://deno.land/x/[email protected]/mod.ts";

// Initialize the plugin
await init();

const client = new MongoClient();
client.connectWithUri("mongodb://localhost:27017");

const db = client.database("test");
const users = db.collection("users");

// insert
const insertId = await users.insertOne({
username: "user1",
password: "pass1"
});

Server shutdown Issue !Important

Server shutdown when the following actions take place

  1. Finding a record with invalid document id
  2. Trying to update with invalid document id tho this can be resolve easily if number issues is fixed

Handeling errors for invalid mongo id

When I try to use updateOne or findOne for invalid mongo id. It is throwing the error shown in the image and crashing the server program. I am totally new to Deno. How can I handle this error? Any kind of help will be appreciated.
Here is my the part of code for findOne


import {Friend} from '../helpers/dbconnect.ts';

export const getFriend: any = async(context: any)=> {
    try{
        let id: string = context.params.id;

        const data :any = await Friend.findOne({_id: {"$oid": id}});    
        if(data){
            context.response.body = data;
            context.response.status = 200;    
        } else {
            context.response.body = "not found";
            context.response.status = 204; 
        }
    }
    catch(e) {
        context.response.body = null;
        context.response.status = 500
        console.log(e);
    }
}

Screenshot from 2020-05-16 20-00-11

deno_mongo uses replica information from primary instead of URL

We have a replica set on MongoDB configured with hosts set in the /etc/hosts file which don't exist on our development machines. When using a URL with the actual domains that are public, deno_mongo uses the information from the primary server instead of the URL. This is not the behaviour we get with Node's MongoDB or with MongoDB Compass (which both use the servers in the connection URL).

thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: ServerSelectionError { message: "Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: premid:27017, Type: Unknown, Error: The supplied Host is unknown. (os error 11001) }, { Address: premid2:27017, Type: Unknown, Error: The supplied Host is  (os error 11001) }, { Address: premid3:27017, Type: Unknown, Error: The supplied Host is (os error 11001) }, ] }" } }', src\command\find.rs:41:26

createIndexes: panicked at 'not implemented'

when trying to create an index like below,

users.createIndexes([
  {
    keys: { email: 1 },
    options: { unique: true },
  },
]);

i get this error:

api_1  | [IndexModel { keys: OrderedDocument({"email": I64(1)}), options: Some(OrderedDocument({"unique": Boolean(true)})) }]
api_1  | thread '<unnamed>' panicked at 'not implemented', <::std::macros::panic macros>:2:4
api_1  | note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

am i calling it wrong, or does not implemented mean here that its not ready to be called yet?

tia

Error while running deno run command

I am getting the following error while running the code with : deno run --allow-net --allow-write --allow-read --allow-plugin --unstable deno-mongo.ts

Screenshot 2020-05-19 at 12 33 01 PM

use deno 0.42.0 get error

I cannot use this lib for deno 0.42.0 in local.
I believe some built in func in Deno does not support some files in deno_mongo
Deno.xxx some func in deno 0.42.0 already remove

The official example does not work on Linux "Debian 9"

Hi, run the example program on W10 and it worked OK. But, when I want to run the same program on Debian. The following error appears:

thread '<unnamed>' panicked at 'called `Option :: unwrap ()` on a `None` value', src / command / connect.rs: 63: 24
note: run with `RUST_BACKTRACE = 1` environment variable to display a backtrace
fatal runtime error: failed to initiate panic, error 5

I have installed:

  • ย  deno 1.0.5
  • ย ย ย  v8 8.4.300
  • ย ย ย ย  typescript 3.9.2

With:

  • MongoDB shell version v4.2.3
  • distmod: debian92
  • distarch: x86_64
  • target_arch: x86_64

Please, someone explain the error and how it is solved.

Couple of errors when i try to run the code on Windows machine

Hello, i'm very happy to know tha a mongo driver is available with deno but there are a couple of errors when i try to execute in widows: this is the error below

Compile https://deno.land/x/[email protected]/mod.ts
error TS2694: Namespace 'Deno' has no exported member 'PluginOp'.
let dispatcher: Deno.PluginOp | null = null;
                     ~~~~~~~~
    at https://deno.land/x/[email protected]/ts/util.ts:7:22

error TS2339: Property 'ops' does not exist on type 'number'.
  dispatcher = Mongo.ops["mongo_command"] as Deno.PluginOp;
                     ~~~
    at https://deno.land/x/[email protected]/ts/util.ts:32:22

error TS2694: Namespace 'Deno' has no exported member 'PluginOp'.
  dispatcher = Mongo.ops["mongo_command"] as Deno.PluginOp;
                                                  ~~~~~~~~
    at https://deno.land/x/[email protected]/ts/util.ts:32:51

error TS2694: Namespace 'Deno' has no exported member 'OperatingSystem'.
const PLUGIN_SUFFIX_MAP: { [os in Deno.OperatingSystem]: string } = {
                                       ~~~~~~~~~~~~~~~
    at https://deno.land/x/[email protected]/mod.ts:9:40

error TS7053: Element implicitly has an 'any' type because expression of type '"darwin" | "linux" | 
"windows"' can't be used to index type '{ mac?: string | undefined; linux?: string | undefined; win?: string | undefined; }'.
  Property 'darwin' does not exist on type '{ mac?: string | undefined; linux?: string | undefined; 
win?: string | undefined; }'.
  const remoteUrl = urls[os];
                    ~~~~~~~~
    at https://deno.land/x/[email protected]/mod.ts:35:21

Found 5 errors.

How to fix it ?

Rust panic

Hello. I didn't touch my previously compiled and running code and I have an error on deno run, seemingly happens while loading the plugin and so it appears from the backtrace, I pasted it here: https://pastebin.com/S7VNTP3P

Edit:
deno 1.0.4 | v8 8.4.300 | typescript 3.9.2

ObjectId() does not throw on invalid strings containing a valid id

When calling ObjectId() with a string that has a valid id somewhere in it, it returns an ObjectId while it should throw an Error.

For example, calling ObjectId() with INVALID-5ec1a815005b1e3000d1e377, 5ec1a815005b1e3000d1e377-INVALID or INVALID-5ec1a815005b1e3000d1e377-INVALID all return an ObjectId, because they contain a valid id (5ec1a815005b1e3000d1e377).

Cannot make projection ?

First, i'd like to thank you for the amazing job you've been doing.

I was playing with Deno and Mongo and I just realized that it was impossible for me to make projection when returning data from a find query.
const productList = await products.find({ }, {name: 1, price:1 , _id:0})
the result of my productList variable contains all products with their price and their id too ...
Am I missing something or is it something that is just not working for the moment ?

add db.collection.distinct() feature

hi, I'm creating a Mongoose like ODM built top of this library. I successfully added nearly all methods except for the distinct method can you please add that method.

https://docs.mongodb.com/manual/reference/method/db.collection.distinct/

this issue is also mentioned in #38
I fork this repo and tried to add that feature by myself but failed to do so that because I'm a beginner to rust.

I hope you add this feature.

and also version 0.8.0 doesn't seem to work on windows.

Connection error

Thread '<unnamed>' panicked at 'called Result::unwrap()on anErr value: Error { kind: ServerSelectionError { message: "Server selection timeout: No available servers. Topology: { Type: Unknown, Servers: [ { Address: localhost:27017, Type: Unknown, Error: failed to fill whole buffer }, ] }" } }'

Is it due to an old version of MongoDB? I'm using the 3.4.9

insertion and update result apis

First of all, I want to thank you about the module.
I jsut want to know if there any restrictions or a use case to return the id of inserted element with insertOne and insertMany; why we don't return the inserted element containing the different attributes with id and also for updating an element too?

How to join two table with aggregate ?

I try to join two collections with aggregate but I didn't. My sample code is here:

const result = await articles.aggregate([
{
$lookup: {
from: "authors",
localField: "oid",
foreignField: "author_id",
as: "author",
},
},
{
$unwind: "$author",
},
]);
req.send(result);

I want an output like the one below. But for now, although there are only 3 Articles in my database, it matches these authors with all authors and brings a total of 6 records.

My Output

I think the problem is caused by the following reason. But I'm not sure.

// My output id format
"_id": {
"$oid": "5ed7abfc00f94b9c0048ba5e"
},

// what will be written in the localfield field in this section
$lookup: {
from: "authors",
localField: "oid",
foreignField: "author_id",
as: "author",
},

How can i solve this problem? I am waiting your help.

Support for sort?

What is this about?

Do we have support for find and sort?

Thanks :)

Please update to Deno v0.39.0

I am not able to import the mongo module after Deno v0.39.0 released. When fetching the module, it gets a 404 error like this.

error: Uncaught Other: Import 'https://deno.land/std/strings/mod.ts' failed: 404 Not Found

After I check the release note, I notice that there is a breaking change that deletes /std/strings/. Can you please make it up to v0.39.0?

DeleteOne crash the app on some cases

I tried something like :

await db.collection('todos').deleteOne({ _id: { $oid: "a" }});

And got my program to crash with the following error :

thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: FromHexError(OddLength)', /home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/bson-0.14.1/src/bson.rs:575:39
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

encountered 6 errors in windows machine (deno latest release v1.0.0rc)

error: TS2694 [ERROR]: Namespace 'Deno' has no exported member 'PluginOp'.
let dispatcher: Deno.PluginOp | null = null;
~~~~~~~~
at https://deno.land/x/[email protected]/ts/util.ts:7:22

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'PluginOp'.
dispatcher = Mongo.ops["mongo_command"] as Deno.PluginOp;
~~~~~~~~
at https://deno.land/x/[email protected]/ts/util.ts:32:51

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'OperatingSystem'.
const PLUGIN_SUFFIX_MAP: { [os in Deno.OperatingSystem]: string } = {
~~~~~~~~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:9:40

TS7053 [ERROR]: Element implicitly has an 'any' type because expression of type '"darwin" | "linux" | "windows"' can't be used to index type '{ mac?: string | undefined; linux?: string | undefined;
win?: string | undefined; }'.
Property 'darwin' does not exist on type '{ mac?: string | undefined; linux?: string | undefined; win?: string | undefined; }'.
const remoteUrl = urls[os];
~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:35:21

TS2339 [ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'.
return Deno.openPlugin(localPath);
~~~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:58:15

Found 5 errors.

C:\Users\DC\Desktop\deno>deno run -A deno-mongo.ts
Compile file:///C:/Users/DC/Desktop/deno/deno-mongo.ts
error: TS2304 [ERROR]: Cannot find name 'getClient'.
const db = getClient().database("test");
~~~~~~~~~
at file:///C:/Users/DC/Desktop/deno/deno-mongo.ts:9:12

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'PluginOp'.
let dispatcher: Deno.PluginOp | null = null;
~~~~~~~~
at https://deno.land/x/[email protected]/ts/util.ts:7:22

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'PluginOp'.
dispatcher = Mongo.ops["mongo_command"] as Deno.PluginOp;
~~~~~~~~
at https://deno.land/x/[email protected]/ts/util.ts:32:51

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'OperatingSystem'.
const PLUGIN_SUFFIX_MAP: { [os in Deno.OperatingSystem]: string } = {
~~~~~~~~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:9:40

TS7053 [ERROR]: Element implicitly has an 'any' type because expression of type '"darwin" | "linux" | "windows"' can't be used to index type '{ mac?: string | undefined; linux?: string | undefined;
win?: string | undefined; }'.
Property 'darwin' does not exist on type '{ mac?: string | undefined; linux?: string | undefined; win?: string | undefined; }'.
const remoteUrl = urls[os];
~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:35:21

TS2339 [ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'.
return Deno.openPlugin(localPath);

C:\Users\DC\Desktop\deno>deno run -A deno-mongo.ts
Compile file:///C:/Users/DC/Desktop/deno/deno-mongo.ts
error: TS2304 [ERROR]: Cannot find name 'getClient'.
const db = getClient().database("test");
~~~~~~~~~
at file:///C:/Users/DC/Desktop/deno/deno-mongo.ts:9:12

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'PluginOp'.
let dispatcher: Deno.PluginOp | null = null;
~~~~~~~~
at https://deno.land/x/[email protected]/ts/util.ts:7:22

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'PluginOp'.
dispatcher = Mongo.ops["mongo_command"] as Deno.PluginOp;
~~~~~~~~
at https://deno.land/x/[email protected]/ts/util.ts:32:51

TS2694 [ERROR]: Namespace 'Deno' has no exported member 'OperatingSystem'.
const PLUGIN_SUFFIX_MAP: { [os in Deno.OperatingSystem]: string } = {
~~~~~~~~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:9:40

TS7053 [ERROR]: Element implicitly has an 'any' type because expression of type '"darwin" | "linux" | "windows"' can't be used to index type '{ mac?: string | undefined; linux?: string | undefined;
win?: string | undefined; }'.
Property 'darwin' does not exist on type '{ mac?: string | undefined; linux?: string | undefined; win?: string | undefined; }'.
const remoteUrl = urls[os];
~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:35:21

TS2339 [ERROR]: Property 'openPlugin' does not exist on type 'typeof Deno'.
return Deno.openPlugin(localPath);
~~~~~~~~~~
at https://deno.land/x/[email protected]/mod.ts:58:15

Found 6 errors.

SelectionCriteria is missing on find query

Hi ๐Ÿ˜„!
I wanted to excluded some attribute on my find() Mongodb query but I can't.
Indeed, On your find() implementation, I didn't found the selectionCriteria (only filter & findOptions are provided).

Mongodb documentation : here

Mongo rust driver find() implementation : here

Mongo data schema

In order to maintain a well-structured program, you need to provide the functionality to define a mongoDB document scheme.

features should also include duplicate entry for field like email

Segmentation fault

Segmentation fault

deno run --allow-read --allow-write --allow-net --allow-run --unstable --allow-plugin index.ts
INFO load deno plugin "deno_mongo" from local "/home/mick/projects/backup-project/.deno_plugins/deno_mongo_2970fbc7cebff869aa12ecd5b8a1e7e4.so"
Segmentation fault (core dumped)
  • Ubuntu 20.04
  • deno 1.0.2
  • v8 8.4.300
  • typescript 3.9.2

unable to handle panic and app get close

here is the error details
thread '' panicked at 'called Result::unwrap() on an Err value: Error { kind: WriteError(WriteError(WriteError { code: 11000, code_name: None, message: "E11000 duplicate key error collection: hops.users index: email_1 dup key: { email: "[email protected]" }" })) }', src/command/insert.rs:32:29
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

and this doesn't get into the catch block, but the app stop its execution.
how can i handle this panic at deno side.

Error handling

How can I handle query error?
I have created a unique index, but how can I detect whether the error code is 11000

Can't compare Date object

await this.webhooksModel.insertMany([
  {
    ...data,
    nextSchedule: new Date()
  }
])

await this.webhooksModels.find(
  {
    nextSchedule: { $lte: new Date() } // new Date(new Date().toISOString())
  }
)

// returns []

If the data type was (new Date).toISOString() it will return data with the following query

await this.webhooksModel.insertMany([
  {
    ...data,
    nextSchedule: (new Date()).toISOString()
  }
])

await this.webhooksModels.find(
  {
    nextSchedule: { $lte: new Date(new Date().toISOString()) }
  }
)

// returns [...data]

However, this will cause problems in the MongoDB itself. We are unable to sort the data if the data type was string instead of Date

insertOne() panicks when trying to send a duplicate index

I tried inserting a record that already exists in Mongo and it panicked and didn't send the error correctly back to Deno.

thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: WriteError(WriteError(WriteError{ code: 11000, code_name: None, message: "E11000 duplicate key error collection: test.users index: id_1 dup key: { id: null}" })) }', src/command/insert.rs:32:29 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Close manually client connection to database

I can't found any indication on how to close client connection from database (instead of using a timeout property in clientOptions).
If I take the example of the node mongodb-native, I think the close() method on the Mongo client is missing (see : here) on this lib. ๐Ÿค”

Error on windows - Rust error

Microsoft Windows [version 10.0.18363.900]
deno 1.1.3
v8 8.5.216
typescript 3.9.2
INFO load deno plugin "deno_mongo" from local "D:\WorkFolder\Devlopment\Peoples Project\Deno\deno-rest-api\.deno_plugins\deno_mongo_7117ccb53f8978e745db83130ae27b42.dll"
thread '<unnamed>' panicked at 'called `Option::unwrap()` on a `None` value', src\command\connect.rs:63:24
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Segmentation fault

Generate ObjectId

It'd be great if there were some way to generate an ObjectId. If there is, please show me how.

Thanks

UpdateOne panicks and crash

thread '' panicked at 'called Result::unwrap() on an Err value: FromHexError(InvalidHexCharacter { c: 's', index: 0 })', C:\Users\runneradmin.cargo\registry\src\github.com-1ecc6299db9ec823\bson-0.14.1\src\bson.rs:575:39
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

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.