问题
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.
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.
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).
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.
I do NOT get an error, but "KEY" is always undefined
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.
I DO GET A RESULT in my Mongo IDE. the record is there....
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 );
}
});
})
Here are the results of the above:
--- module.exports.findKey --- zzc6a
ha ha --- zzc6a
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);
}
I have tried this
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] }
回答1:
From your code
module.exports.findKey = function( key, callback ) {
console.log('--- module.exports.findKey --- ' + key );
const query = { key: key };
CouponKey.find(query, callback);
}
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 );
}
});
And for mongoose if you want only 1 record you can use function findOne
instead of find
, it will return an object
About the code blow
const query = { key: key };
x = UserKey.find(query);
console.log(x);
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.
来源:https://stackoverflow.com/questions/48574699/mongoose-not-returning-a-record