猫鼬不返回记录

mongoose not returning a record

好吧,昨晚我发布了一个问题,因为我对在方法调用中混入 return 感到沮丧;我得到了一个有效的答案,但我很困惑,因为这是我在问题发生之前所做的。

问题在这里: 如您所知,我正在 "KEY" 回来...它只是在对象和对象数组之间波动。

今晚 - 我坐下来继续,现在我什至无法从 "findKey" 电话中取回 KEY。 (从昨晚的那期起向上一步)。

objective是兑换优惠券。 用户将 url 中的 KEY 传递给 api,这将 1) 按键查找记录,return 一个 id 和用户 id(发给 'Coupon' 的人) 2) 如果优惠券未被兑换,则会标记优惠券已兑换 3) 和有问题的用户一起做其他事情。

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

mongoDB Atlas - mongooseJS 4.9.8 - node 8.9.1 - express 4.15.5 键是 128 个字符的 UID - 如果这对猫鼬有影响,我已经用 5 个字符键尝试过并得到相同的 'no result' 所以我认为这不是问题。

我确实在 Mongo IDE 中取得了成果。记录在那里....

兑换优惠券的路线

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

型号优惠券密钥

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);

输出是这样的(我没看到'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的结果总是一个数组。因此,如果它没有任何结果,它将 return 一个空数组 []。你的回调只检查它是否 undefined,我认为你应该在检查之前记录键值以了解你得到了什么并检查错误。

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 ,它将 return 一个对象

关于代码吹

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

函数find return 猫鼬查询不是您记录中的对象。如果你需要记录,你必须通过回调或使用promise。