如何从Mongoose查询中检索数据?

时间:2017-08-19 16:55:48

标签: node.js mongodb mongoose mean-stack

我使用mongoose作为我的ORM在MEAN堆栈中编写应用程序。

我正在CRUD过程中实现创建和读取操作。

我的页面架构如下

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指南针

所示的create函数的结果

the create function worked

读取功能的测试:

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

以上是上述函数中console.log的结果

    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] }

只是为了获得额外的帮助,今天是我的MongoDB日志(太大了,不适合这里): mongodb.log

问题的最后部分:

如何进行查找操作返回创建函数的结果,如MongoDB罗盘图片所示?我已经绞尽脑汁三天试图解决这个问题并且不明白我做错了什么。对所涉及的过程的任何帮助或解释都将非常有用。

1 个答案:

答案 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);
}

参考上面的读取函数定义,你的第三个参数是回调,当你返回结果时,你没有使用回调。