问题
Hi Guys i try to do some email verification after a user suscrib to my api but when i do user.FindOne(token), the user is find but i not able to get the value of the user in the database the return me a big ass array and i don't see wich value to choose. my code:
ValidationFunction:
const User = require('../models/User');
const Token = require('../models/Token');
module.exports = function (req, res, next) {
const headToken = req.header('token');
const token = Token.findOne({ token: headToken })
if (!token) {
return res.status(400).send('We were unable to find a valid token. Your token my have expired.')
} else {
console.log(token);
}
try {
const user = User.findOne({ _id: token._userId})
if (!user) return res.status(400).send('We were unable to find a user for this token.');
if (user.isVerified) console.log('déja vérifié');;
// Verify and save the user
user.isVerified = true;
user.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }
res.status(200).send("The account has been verified. Please log in.");
});
next();
} catch (err) {
res.status(400).send('Invalid Token');
}
}
if i do console.log(token._userId) or console.log(token._id) i got undefined but if i do console.log(token) i got this:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map {}, _posts: Map {} },
_executionCount: 0,
mongooseCollection: NativeCollection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
_closed: false,
opts: {
bufferCommands: true,
capped: false,
autoCreate: undefined,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'tokens',
collectionName: 'tokens',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
plugins: [],
id: 0,
_listening: false,
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
name: 'test',
host: 'cluster0-shard-00-01-1lzx5.mongodb.net',
port: xxxxx,
user: 'xxxx',
pass: 'xxxx',
db: [Db]
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Token },
schema: Schema {
obj: { _userId: [Object], token: [Object], createdAt: [Object] },
paths: {
_userId: [ObjectId],
token: [SchemaString],
createdAt: [SchemaDate],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
_userId: [Object],
token: [Object],
createdAt: [Object],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 2,
s: { hooks: [Kareem] },
_userProvidedOptions: {},
options: {
typePojoToMixed: true,
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: 'findOne',
options: {},
_conditions: { token: '05bfd1ff19ef015934e04d2a8f21d37d' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: NativeCollection {
collection: [Collection],
Promise: [Function: Promise],
_closed: false,
opts: [Object],
name: 'tokens',
collectionName: 'tokens',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'tokens'
},
_traceFunction: undefined,
'$useProjection': true
}
回答1:
findOne
returns a promise, you need to wait for it resolve to read the values.
change your function into this:
module.exports = async function (req, res, next) {
const headToken = req.header('token');
const token = await Token.findOne({ token: headToken })
...
}
来源:https://stackoverflow.com/questions/61826961/mongodb-findone-not-return-value-nodejs