猫鼬不返回记录

猫鼬不返回记录

问题描述:

好吧,昨晚我发布了一个问题,因为我很沮丧地在方法调用中获得混合的回报;我得到了一个行之有效的答案,但让我感到困惑,因为那是我在问题发布之前所做的事情.

Well, Last night I posted a question because I was frustrated getting mixed returns on a method call; I got an answer that worked, but I was left confused because it's what I was doing before the issue.

该问题在此处: javascript undefined,何时我刚刚登录了 正如您所知道的,我正在找回关键"……它只是在作为对象和对象数组之间波动.

That question is here: javascript undefined, when I just logged it and as you can tell, I WAS GETTING "KEY" BACK...it was just fluctuating between being an object and an array of objects.

今晚-我坐下来继续学习,现在我什至无法从"findKey"电话找回KEY. (从昨晚发行的文件中向上升级).

Tonight - I sit down to resume, and NOW I cant even get KEY back from the "findKey" call. (one step UP the chain from last nights issue).

目标是兑换一张优惠券. 用户将url中的KEY传递给api, 1)通过键查找记录,返回ID和用户ID(向其颁发优惠券"的用户) 2)如果尚未兑换优惠券,它将标记为已兑换的优惠券 3)并与有问题的用户做其他事情.

The objective is to redeem a Coupon. The user will pass a KEY in the url to an api, which will 1) look up the record by key, return an id and user id (to who the 'Coupon' was issued) 2) if the Coupon has NOT been redeemed, it will mark the coupon redeeded 3) and do other stuff with the user in question.

我没有收到错误消息,但"KEY"始终未定义

I do NOT get an error, but "KEY" is always undefined

mongoDB Atlas-mongooseJS 4.9.8-节点8.9.1-Express 4.15.5 密钥是128个字符的UID-如果对猫鼬有影响,我尝试使用5个字符的密钥进行尝试,并得到相同的无结果" 所以我认为这不是问题.

mongoDB Atlas - mongooseJS 4.9.8 - node 8.9.1 - express 4.15.5 the keys are 128 char UIDs - if that has an effect on mongoose, I've tried it with 5 char Keys and get the same 'no result' so I don't think that is the issue.

我确实在我的Mongo IDE中得到了结果.记录在那里....

I DO GET A RESULT in my Mongo IDE. the record is there....

ROUTE兑换优惠券

ROUTE to redeem coupon

router.get('/:_key', (req,res) => {

    CouponKey.findKey( req.params._key, (err, key) => { 

        if ( key !== undefined ) { // sadly this was working last night - 

            console.log( 'yea ---' + key );

        } else { // now this is all i get

            console.log('ha ha --- ' + req.params._key );

        }

    });

})

以下是上述结果:

--- module.exports.findKey --- zzc6a
ha ha --- zzc6a

MODEL CouponKey

MODEL CouponKey

const CouponKeySchema = new Schema({
    key: {
        type: String
        ,required: true
    }
    ,type: {
        type: String
        ,required: true
    }
    ,user_id: {
        type: mongoose.Schema.ObjectId
        ,required: true
    }
    ,date: {
        issued: {
            type: Date
            ,default: Date.now
        }
        ,redeemed: {
            type: Date
            ,default: null
        }
    }
}, {collection:'coupons_keys',strict:false } );

const CouponKey = module.exports = mongoose.model('CouponKey', CouponKeySchema);

module.exports.findKey = function( key, callback ) {

    console.log('--- module.exports.findKey --- ' + key );

    const query = { key: key };
    CouponKey.find(query, callback);

}

我已经尝试过

const query = { key: key };
x = UserKey.find(query);
console.log(x);

输出是这个(我没有看到返回记录")

the output is this (I did not see a 'return record')

Query {
  _mongooseOptions: {},
  mongooseCollection:
   NativeCollection {
     collection: Collection { s: [Object] },
     opts: { bufferCommands: true, capped: false },
     name: 'coupons_keys',
     collectionName: 'coupons_keys',
     conn:
      NativeConnection {
        ... },
     queue: [],
     buffer: false,
     emitter:
      EventEmitter {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined } },
  model:
   { [Function: model]
     hooks: Kareem { _pres: {}, _posts: {} },
     base:
      Mongoose {
        connections: [Array],
        plugins: [],
        models: [Object],
        modelSchemas: [Object],
        options: [Object] },
     modelName: 'CouponKey',
     model: [Function: model],
     db:
      NativeConnection {
        ... },
     discriminators: undefined,
     schema:
      Schema {
        obj: [Object],
        paths: [Object],
        subpaths: {},
        virtuals: [Object],
        singleNestedPaths: {},
        nested: [Object],
        inherits: {},
        callQueue: [Array],
        _indexes: [],
        methods: {},
        statics: {},
        tree: [Object],
        query: {},
        childSchemas: [],
        _plugins: [Object],
        s: [Object],
        options: [Object],
        '$globalPluginsApplied': true },
     collection:
      NativeCollection {
        collection: [Object],
        opts: [Object],
        name: 'coupons_keys',
        collectionName: 'coupons_keys',
        conn: [Object],
        queue: [],
        buffer: false,
        emitter: [Object] },
     Query: { [Function] base: [Object] },
     '$__insertMany': [Function],
     insertMany: [Function],
     setKey: [Function],
     findKey: [Function],
     findKeyByCouponId: [Function],
     redeem: [Function] },
  schema:
   Schema {
     obj:
      { key: [Object],
        type: [Object],
        coupon_id: [Object],
        date: [Object] },
     paths:
      { key: [Object],
        type: [Object],
        coupon_id: [Object],
        'date.issued': [Object],
        'date.redeemed': [Object],
        _id: [Object],
        __v: [Object] },
     subpaths: {},
     virtuals: { id: [Object] },
     singleNestedPaths: {},
     nested: { date: true },
     inherits: {},
     callQueue: [ [Array], [Array], [Array], [Array] ],
     _indexes: [],
     methods: {},
     statics: {},
     tree:
      { key: [Object],
        type: [Object],
        coupon_id: [Object],
        date: [Object],
        _id: [Object],
        id: [Object],
        __v: [Function: Number] },
     query: {},
     childSchemas: [],
     _plugins: { saveSubdocs: true, validateBeforeSave: true },
     s: { hooks: [Object], kareemHooks: [Object] },
     options:
      { collection: 'coupons_keys',
        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:
   { key: 'qJ5qb...' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection:
   NodeCollection {
     collection:
      NativeCollection {
        collection: [Object],
        opts: [Object],
        name: 'coupons_keys',
        collectionName: 'coupons_keys',
        conn: [Object],
        queue: [],
        buffer: false,
        emitter: [Object] },
     collectionName: 'coupons_keys' },
  _traceFunction: undefined,
  _castError: null,
  _count: [Function],
  _execUpdate: [Function],
  _find: [Function],
  _findOne: [Function],
  _findOneAndRemove: [Function],
  _findOneAndUpdate: [Function],
  _replaceOne: [Function],
  _updateMany: [Function],
  _updateOne: [Function] }

来自您的代码

 module.exports.findKey = function( key, callback ) {

    console.log('--- module.exports.findKey --- ' + key );

    const query = { key: key };
    CouponKey.find(query, callback);

}

函数find的结果始终是一个数组.因此,如果没有任何结果,它将返回一个空数组[].您的回调仅检查它是否为undefined,我认为您应该在检查之前记录键值以知道得到了什么并检查错误.

The result from function find is always an Array. So if it doesn't have any result it will return an empty array []. Your callback only check if it undefined, I think you should log key value before check to know what you get and check error, too.

CouponKey.findKey( req.params._key, (err, key) => { 
        console.log(err);
        console.log(key);

        if ( key !== undefined ) { // sadly this was working last night - 

            console.log( 'yea ---' + key );

        } else { // now this is all i get

            console.log('ha ha --- ' + req.params._key );

        }

    });

对于猫鼬,如果只需要1条记录,则可以使用函数findOne代替find,它将返回一个对象

And for mongoose if you want only 1 record you can use function findOne instead of find , it will return an object

关于代码的打击

const query = { key: key };
x = UserKey.find(query);
console.log(x);

函数find返回猫鼬查询,而不是记录中的对象.如果需要记录,则必须传递回调或使用Promise.

Function find return a mongoose Query not an object from your record. If you need the record, you have to pass a callback or use promise.