2017-08-19 11 views
0

私はORANとしてmongooseを使ってMEANスタックにアプリを書いています。Mongooseクエリからデータを取得する方法は?

私はCRUDプロセスでCreate操作とRead操作を実装しています。

const mongoose = require('mongoose'); 
var pageSchema = new moongose.Schema({ 
pageExtension:{ 
    type:String, 
    default:"html" 
}, 
publicFileRoot:{ 
    type:String, 
    default:"/dist/" 
}, 
testAttribute:{ 
    type:String 
}, 
title:{ 
    type:String, 
    required:[true ,'title is required'] 
}, 
pageName:{ 
    type:String, 
    required:[true, "the page name for this page is required"] 
}, 
routeUri:{ 
    type:String 
}, 
projects:[{ 
    type:Schema.Types.ObjectId, ref:projectSchema 
}], 
fileUrl:{ 
    type:String, 
    required:[true, "the file url is requred"], 
    default:this.publicFileRoot + this.pageName 
}, 
pageID:{ 
    type:Number, 
    index:true, 
    unique:true, 
    required:true 
}, 
webUrl:{ 
    type:String 
}, 
lastUpdated:{type:Date, default:Date.now, required:[true, 'the last updated Date is required']}, 
_mongoID: {type:Schema.Types.ObjectId, description:"mongoDB's Unique ID"}, 
staticFiles:{ 
    css:{ 
     type:Array, 
     url:{ 
      type:String 
     } 
    }, 
    js:[{ 
     type:Array, 
     url:{ 
      type:String 
     } 
    }], 
    html:[{ 
     url:{ 
      type:String 
     } 
    }], 
    img:[{ 
     type:Array, 
     imgID:{ 
      type:String 
     }, 
     imgUrl:{ 

     } 

    }] 
} 
}); 
module.exports = pageSchema; 

作成機能の

var mongoose = require('mongoose'), 
var mongoDB = 'mongodb://127.0.0.1/test'; 
var conn = mongoose.createConnection(mongoDBConnectionURI,{useMongoClient:true}) 
.on('connected',function(){ 
    console.log("connected to database"); 
}); 
var pageModel = conn.model('PageModel',pageSchema); 
var readCallback = function(err,doc){ 
    if(err){ 
     console.error.bind(console,err); 
    } 
    else{ 
    return doc.collections; 
    } 
} 
var create = function(Model,options = {}{ 
var newDocument = new Model(options); 
validationError = newDocument.validateSync(); 
if(validationError){ 
    console.log("on create: validation error:" + validationError); 
} 
else{ 
    newDocument.save(function(err,newDocument){ 
     if(err) return console.log(err); 
     else return newDocument; 
    }); 
} 
} 
//this function should query the database and return the result of the query 
var read = function(Model, options, callback){ 
//options should contain an object with the format {attribute:value} 
//check if the Model variable is defined 
if(Model===undefined){ 
// the model reference is required 
    throw new Error("Error on db.read: Model is undefined"); 
} 
//check if the attribute 
else if(options.attribute === undefined){ 
    //if no attribute is specified then just return the result of a model.find operation 
    return Model.find({attribute:value},readCallback); 
} 
else{ 
    //if value is undefined assume user wants to return all results limited to attribute only 
    if(options[options.attribute] === undefined){ 

     return Model.find({}) 
      .exec(
        function(err,doc){ 
        if (err) console.error.bind(console,error); 
        else return doc; 
      }); 
    } 
    //model, attribute, value are defined. perform a specific search 
    else{ 

      return Model.findOne(options,readcallback); 
     } 
    } 
    } 
} 

テスト、次のように私のデータベーススクリプトが次のようにマイページのスキーマは次のとおりです。ここで

create(pageModel, 
{ 
    pageName:"testpage 1", 
    title:"testing the functioning of the database", 
    pageID:4 
}, 
); 

が作成した結果であるがMongoDBコンパスが示すような機能

読み取り機能の

the create function worked

テスト:ここ

console.log(pageModel.find({"pageName":"testpage 1"},readCallback);

ちょうど余分な助けを

Query { 
    _mongooseOptions: {}, 
    mongooseCollection: 
    NativeCollection { 
    collection: null, 
    opts: { bufferCommands: true, capped: false }, 
    name: 'pagemodels', 
    collectionName: 'pagemodels', 
    conn: 
     NativeConnection { 
     base: [Object], 
     collections: [Object], 
     models: [Object], 
     config: [Object], 
     replica: false, 
     hosts: null, 
     host: null, 
     port: null, 
     user: null, 
     pass: null, 
     name: null, 
     options: null, 
     otherDbs: [], 
     _readyState: 2, 
     _closeCalled: false, 
     _hasOpened: false, 
     _listening: false, 
     _connectionOptions: {}, 
     then: [Function], 
     catch: [Function], 
     _events: [Object], 
     _eventsCount: 1 }, 
    queue: [], 
    buffer: true, 
    emitter: 
     EventEmitter { 
     domain: null, 
     _events: {}, 
     _eventsCount: 0, 
     _maxListeners: undefined } }, 
    model: 
    { [Function: model] 
    hooks: Kareem { _pres: {}, _posts: {} }, 
    base: 
     Mongoose { 
     connections: [Array], 
     models: {}, 
     modelSchemas: [Object], 
     options: [Object], 
     plugins: [Array] }, 
    modelName: 'PageModel', 
    model: [Function: model], 
    db: 
     NativeConnection { 
     base: [Object], 
     collections: [Object], 
     models: [Object], 
     config: [Object], 
     replica: false, 
     hosts: null, 
     host: null, 
     port: null, 
     user: null, 
     pass: null, 
     name: null, 
     options: null, 
     otherDbs: [], 
     _readyState: 2, 
     _closeCalled: false, 
     _hasOpened: false, 
     _listening: false, 
     _connectionOptions: {}, 
     then: [Function], 
     catch: [Function], 
     _events: [Object], 
     _eventsCount: 1 }, 
    discriminators: undefined, 
    '$appliedHooks': true, 
    _events: { init: [Function], save: [Function] }, 
    _eventsCount: 2, 
    schema: 
     Schema { 
     obj: [Object], 
     paths: [Object], 
     aliases: {}, 
     subpaths: {}, 
     virtuals: [Object], 
     singleNestedPaths: {}, 
     nested: [Object], 
     inherits: {}, 
     callQueue: [Array], 
     _indexes: [], 
     methods: {}, 
     statics: {}, 
     tree: [Object], 
     query: {}, 
     childSchemas: [Array], 
     plugins: [Array], 
     s: [Object], 
     options: [Object], 
     '$globalPluginsApplied': true }, 
    collection: 
     NativeCollection { 
     collection: null, 
     opts: [Object], 
     name: 'pagemodels', 
     collectionName: 'pagemodels', 
     conn: [Object], 
     queue: [], 
     buffer: true, 
     emitter: [Object] }, 
    Query: { [Function] base: [Object] }, 
    '$__insertMany': [Function], 
    insertMany: [Function] }, 
    schema: 
    Schema { 
    obj: 
     { pageExtension: [Object], 
     publicFileRoot: [Object], 
     testAttribute: [Object], 
     title: [Object], 
     pageName: [Object], 
     routeUri: [Object], 
     projects: [Array], 
     fileUrl: [Object], 
     pageID: [Object], 
     webUrl: [Object], 
     lastUpdated: [Object], 
     _mongoID: [Object], 
     staticFiles: [Object] }, 
    paths: 
     { pageExtension: [Object], 
     publicFileRoot: [Object], 
     testAttribute: [Object], 
     title: [Object], 
     pageName: [Object], 
     routeUri: [Object], 
     projects: [Object], 
     fileUrl: [Object], 
     pageID: [Object], 
     webUrl: [Object], 
     lastUpdated: [Object], 
     _mongoID: [Object], 
     'staticFiles.css': [Object], 
     'staticFiles.js': [Object], 
     'staticFiles.html': [Object], 
     'staticFiles.img': [Object], 
     _id: [Object], 
     __v: [Object] }, 
    aliases: {}, 
    subpaths: {}, 
    virtuals: { id: [Object] }, 
    singleNestedPaths: {}, 
    nested: { staticFiles: true }, 
    inherits: {}, 
    callQueue: [ [Array], [Array], [Array], [Array], [Array], [Array] ], 
    _indexes: [], 
    methods: {}, 
    statics: {}, 
    tree: 
     { pageExtension: [Object], 
     publicFileRoot: [Object], 
     testAttribute: [Object], 
     title: [Object], 
     pageName: [Object], 
     routeUri: [Object], 
     projects: [Array], 
     fileUrl: [Object], 
     pageID: [Object], 
     webUrl: [Object], 
     lastUpdated: [Object], 
     _mongoID: [Object], 
     staticFiles: [Object], 
     _id: [Object], 
     id: [Object], 
     __v: [Function: Number] }, 
    query: {}, 
    childSchemas: [ [Object] ], 
    plugins: [ [Object], [Object], [Object] ], 
    s: { hooks: [Object], kareemHooks: [Object] }, 
    options: 
     { retainKeyOrder: false, 
     typeKey: 'type', 
     id: true, 
     noVirtualId: false, 
     _id: true, 
     noId: false, 
     validateBeforeSave: true, 
     read: null, 
     shardKey: null, 
     autoIndex: null, 
     minimize: true, 
     discriminatorKey: '__t', 
     versionKey: '__v', 
     capped: false, 
     bufferCommands: true, 
     strict: true, 
     pluralization: true }, 
    '$globalPluginsApplied': true }, 
    op: 'find', 
    options: { retainKeyOrder: false }, 
    _conditions: {}, 
    _fields: undefined, 
    _update: undefined, 
    _path: undefined, 
    _distinct: undefined, 
    _collection: 
    NodeCollection { 
    collection: 
     NativeCollection { 
     collection: null, 
     opts: [Object], 
     name: 'pagemodels', 
     collectionName: 'pagemodels', 
     conn: [Object], 
     queue: [], 
     buffer: true, 
     emitter: [Object] }, 
    collectionName: 'pagemodels' }, 
    _traceFunction: undefined, 
    _count: [Function], 
    _execUpdate: [Function], 
    _find: [Function], 
    _findOne: [Function], 
    _findOneAndRemove: [Function], 
    _findOneAndUpdate: [Function], 
    _replaceOne: [Function], 
    _updateMany: [Function], 
    _updateOne: [Function] } 

上記の機能にはconsole.logの結果であり、ここに私のMongoDBはです今日のログ(このサイズに合わせるには大きかった): mongodb.log

質問の最後の部分:

MongoDBコンパスの画像に示されているように、find関数の結果を返すにはどうすればよいですか?私はこれを理解しようと3日間私の脳をぶら下げているし、私が間違っていることを理解していない。関係するプロセスの助けや説明はとても役に立ちます。上記の読み取り機能の定義を参照して

+0

私はもともとパスワードを使ってアカウント管理者を使ってデータベースに接続しようとしましたが、失敗し、今すぐ削除しました –

答えて

0
//this function should query the database and return the result of the  query 
var read = function(Model, options, callback){ 
//options should contain an object with the format {attribute:value} 
//check if the Model variable is defined 
if(Model===undefined){ 
// the model reference is required 
throw new Error("Error on db.read: Model is undefined"); 
} 
//check if the attribute 
else if(options.attribute === undefined){ 
    //if no attribute is specified then just return the result of a model.find operation 
return Model.find({attribute:value},readCallback); 
} 

あなたの3番目のパラメータは、コールバックとするとき、あなたがコールバックを使用していない結果を返すされています。

+0

コード例を教えたり、 –

+0

3番目のパラメータ 'callback'を削除してから、関数を呼び出してみてください。 –

関連する問題