mongo drive 中 find fields功能实现

This commit is contained in:
yinlainghui 2019-03-28 17:53:19 +08:00
parent ffb39a96bb
commit 3529871c0c
2 changed files with 66 additions and 3 deletions

View File

@ -48,10 +48,21 @@ export class SteedosMongoDriver implements SteedosDriver {
}
/* TODO */
getMongoOptions(filters: SteedosQueryOptions){
return {
//projection: {_id: 1}
getMongoOptions(options: SteedosQueryOptions): JsonMap {
if (_.isUndefined(options)) {
return {}
}
let fields: string[] = options.fields;
if (_.isUndefined(fields)) {
return {}
}
let result: JsonMap = {};
let projection: JsonMap = {};
fields.forEach((field)=>{
projection[field] = 1;
});
result.projection = projection;
return result;
}
collection(name: string) {

View File

@ -0,0 +1,52 @@
import { SteedosMongoDriver } from "../../../../src/driver";
import { expect } from 'chai';
let tableName = "mongo-driver-test-fields";
describe('fetch records width specific fields', () => {
before(async ()=>{
let mongo = new SteedosMongoDriver({ url: "mongodb://127.0.0.1/steedos" });
await mongo.connect();
await mongo.collection(tableName).deleteMany()
});
it('fetch only some specific fields', async () => {
let mongo = new SteedosMongoDriver({ url: "mongodb://127.0.0.1/steedos" });
await mongo.connect();
await mongo.insert(tableName, { _id: "ptr", name: "ptr", title: "PTR" })
await mongo.insert(tableName, { _id: "cnpc", name: "cnpc", title: "CNPC" })
let queryOptions = {
fields: ["name"]
};
let result = await mongo.find(tableName, queryOptions);
console.log("fetch records width specific fields result:");
console.log(result);
await mongo.delete(tableName, "ptr");
await mongo.delete(tableName, "cnpc");
expect(result).to.be.length(2);
expect(result[0].name).to.be.eq("ptr");
expect(result[0].title).to.be.eq(undefined);
});
it('fetch all fields', async () => {
let mongo = new SteedosMongoDriver({ url: "mongodb://127.0.0.1/steedos" });
await mongo.connect();
await mongo.insert(tableName, { _id: "ptr", name: "ptr", title: "PTR" })
await mongo.insert(tableName, { _id: "cnpc", name: "cnpc", title: "CNPC" })
let queryOptions = {
};
let result = await mongo.find(tableName, queryOptions);
console.log("fetch records width specific fields result:");
console.log(result);
await mongo.delete(tableName, "ptr");
await mongo.delete(tableName, "cnpc");
expect(result).to.be.length(2);
expect(result[0].name).to.be.eq("ptr");
expect(result[0].title).to.be.eq("PTR");
});
});