Skip to content

Commit

Permalink
Update options (#75)
Browse files Browse the repository at this point in the history
Add options to update #75
  • Loading branch information
lucacasonato authored Jul 11, 2020
1 parent d4cc3df commit 2503375
Show file tree
Hide file tree
Showing 7 changed files with 82 additions and 12 deletions.
2 changes: 1 addition & 1 deletion mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export * from "./ts/client.ts";
export * from "./ts/collection.ts";
export * from "./ts/database.ts";
export * from "./ts/result.ts";
export { ObjectId } from "./ts/types.ts";
export { ObjectId, UpdateOptions } from "./ts/types.ts";
export * from "./ts/util.ts";
export const VERSION = "v0.8.0";
export const RELEASE_URL =
Expand Down
29 changes: 27 additions & 2 deletions src/command/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ struct UpdateArgs {
query: Value,
update: Value,
update_one: bool,
options: Option<UpdateOptions>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct UpdateOptions {
array_filters: Option<Vec<Document>>,
bypass_document_validation: Option<bool>,
upsert: Option<bool>,
// TODO: add collation
// TODO: add hint
// TODO: add write_concern
}

#[derive(Serialize, Debug)]
Expand All @@ -33,13 +45,26 @@ pub fn update(command: Command) -> util::AsyncJsonOp<UpdateResultArgs> {
let database = client.database(&db_name);
let collection = database.collection(&collection_name);

let options = if let Some(option) = args.options {
Some(options::UpdateOptions {
array_filters: option.array_filters,
bypass_document_validation: option.bypass_document_validation,
upsert: option.upsert,
collation: None,
hint: None,
write_concern: None,
})
} else {
None
};

let result = if args.update_one {
collection
.update_one(query_doc, update_doc, None)
.update_one(query_doc, update_doc, options)
.map_err(|e| e.to_string())?
} else {
collection
.update_many(query_doc, update_doc, None)
.update_many(query_doc, update_doc, options)
.map_err(|e| e.to_string())?
};

Expand Down
17 changes: 12 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,21 @@ extern crate bson;
extern crate mongodb;
extern crate serde;

use bson::Document;
use deno_core::plugin_api::{Buf, Interface, Op, ZeroCopyBuf};
use futures::{Future, FutureExt};
use mongodb::Client;
use mongodb::{options, Client};
use serde::{Deserialize, Serialize};
use std::result::Result;
use std::sync::atomic::{AtomicUsize, Ordering};

use std::{clone::Clone, collections::HashMap, pin::Pin, sync::Mutex, sync::MutexGuard};
use std::{
clone::Clone,
collections::HashMap,
pin::Pin,
result::Result,
sync::{
atomic::{AtomicUsize, Ordering},
Mutex, MutexGuard,
},
};

mod command;
mod util;
Expand Down
26 changes: 26 additions & 0 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,32 @@ test("testInsertOne", async () => {
});
});

test("testUpsertOne", async () => {
const db = getClient().database("test");
const users = db.collection<IUser>("mongo_test_users");
const { upsertedId } = await users.updateOne({
_id: ObjectId("aaaaaaaaaaaaaaaaaaaaaaaa"),
}, {
username: "user1",
password: "pass1",
date: new Date(dateNow),
}, { upsert: true });

assert(upsertedId);
assertEquals(Object.keys(upsertedId), ["$oid"]);

const user1 = await users.findOne({
_id: ObjectId(upsertedId.$oid),
});

assertEquals(user1, {
_id: upsertedId,
username: "user1",
password: "pass1",
date: new Date(dateNow),
});
});

test("testInsertOneTwice", async () => {
const db = getClient().database("test");
const users = db.collection<IUser>("mongo_test_users_2");
Expand Down
10 changes: 7 additions & 3 deletions ts/collection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MongoClient } from "./client.ts";
import { UpdateResult } from "./result.ts";
import { CommandType, FindOptions, ObjectId } from "./types.ts";
import { CommandType, FindOptions, ObjectId, UpdateOptions } from "./types.ts";
import { convert, parse } from "./type_convert.ts";
import { dispatchAsync, encode } from "./util.ts";

Expand Down Expand Up @@ -272,6 +272,7 @@ export class Collection<T extends any> {
query: FilterType<T>,
update: FilterType<T>,
updateOne: boolean = false,
options?: UpdateOptions,
): Promise<UpdateResult & T & WithID> {
const result = await dispatchAsync(
{
Expand All @@ -285,6 +286,7 @@ export class Collection<T extends any> {
query: convert(query),
update: convert(update),
updateOne,
options: options ?? null,
}),
),
);
Expand All @@ -294,15 +296,17 @@ export class Collection<T extends any> {
public updateOne(
query: FilterType<T>,
update: FilterType<T>,
options?: UpdateOptions,
): Promise<UpdateResult & T & WithID> {
return this._update(query, update, true);
return this._update(query, update, true, options);
}

public updateMany(
query: FilterType<T>,
update: FilterType<T>,
options?: UpdateOptions,
) {
return this._update(query, update, false);
return this._update(query, update, false, options);
}

public async aggregate<T extends {}>(
Expand Down
4 changes: 3 additions & 1 deletion ts/result.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { ObjectId } from "./types.ts";

export interface UpdateResult {
matchedCount: number;
modifiedCount: number;
upsertedId: Object | null;
upsertedId: ObjectId | null;
}
6 changes: 6 additions & 0 deletions ts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,9 @@ export interface FindOptions {
skip?: number;
limit?: number;
}

export interface UpdateOptions {
arrayFilters?: object[];
bypassDocumentValidation?: boolean;
upsert?: boolean;
}

0 comments on commit 2503375

Please sign in to comment.