Mongoose.js findOne 返回查询元数据
Mongoose.js findOne returning query metadata
我正在尝试 运行 我的数据库中的一个 mongoose.findOne 但我得到了意外 results.My 查询是
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = function findUser(email){
const foundUser = User.findOne({email: email}, function(err, userObj){
if(err){
return err
} else if (userObj){
return userObj
} else{
return null
}
})
return foundUser
}
但是这个 returns 以下数据(看似随机?)并且有 none 我请求的数据
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: null,
opts: { bufferCommands: true, capped: false },
name: 'users',
collectionName: 'users',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'ds113938.mlab.com',
port: 13938,
user: 'root',
pass: 'root',
name: 'users',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] },
queue: [],
buffer: true,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: {}, _posts: {} },
base:
Mongoose {
connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'User',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'ds113938.mlab.com',
port: 13938,
user: 'root',
pass: 'root',
name: 'users',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] },
discriminators: undefined,
schema:
Schema {
obj: [Object],
paths: [Object],
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [Object],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: [Object],
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
insertMany: [Function] },
schema:
Schema {
obj:
{ name: [Function: String],
email: [Function: String],
passwordHash: [Function: String],
validation: [Function: String],
validationCode: [Function: String],
favorites: [Function: Array] },
paths:
{ name: [Object],
email: [Object],
passwordHash: [Object],
validation: [Object],
validationCode: [Object],
favorites: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [ [Object], [Object], [Object], [Object] ],
_indexes: [],
methods: {},
statics: {},
tree:
{ name: [Function: String],
email: [Function: String],
passwordHash: [Function: String],
validation: [Function: String],
validationCode: [Function: String],
favorites: [Function: Array],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
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: 'findOne',
options: { retainKeyOrder: false },
_conditions: { email: 'Adam@gmail.com' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
collectionName: 'users' },
_traceFunction: undefined,
_castError: null,
_count: [Function],
_execUpdate: [Function],
_find: [Function],
_findOne: [Function],
_findOneAndRemove: [Function],
_findOneAndUpdate: [Function] }
我想知道如何解决这个问题,这似乎是我尝试 运行 的查询的概述,而不是所述查询
的结果
试试这个:
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = function findUser(email, callback){
User.findOne({email: email}, function(err, userObj){
if(err){
return callback(err);
} else if (userObj){
return callback(null,userObj);
} else {
return callback();
}
});
}
当您执行 User.findOne 时,猫鼬会在回调中调用 mongodb 和 return 您的用户(findOne 函数中的最后一个参数),因此 return发现用户调用回调。
要调用findUser
函数,你需要传递一个回调函数,像这样:
findUser('adam@gmail.com', function(error, userFound) {
console.log(userFound);
});
您可以找到有关 Mongoose findOne 的更多详细信息here and to learn about callback functions you can take a look here
您看到的是 return foundUser
的结果,一个 Mongoose 查询对象。
您正在混合同步和异步代码,您必须等待查询执行并回调调用它的函数,如下所示:
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array });
exports.findUser = function findUser(email,callback){
const foundUser = User.findOne({email: email}, (err, userObj)=>{
if(err){
callback(err)
} else if (userObj){
callback(null,userObj)
} else {
callback(new Error('Some strange thing has happened));
}
});
}
然后您可以这样调用您的函数:
findUser((err,user)=>{
if(err) console.log(err);
console.log(user)
});
为了快速介绍回调,这是从 What is a callback function?
开始的 link
我最近遇到了同样的问题。
在我的例子中,在运行之前提出了一个解决方案,尽管在这种情况下该方法必须是异步的。
如下:
async findUser(email,callback){
const foundUser = await User.findOne({email: email}, (err, userObj)=>{
if(err){
callback(err)
} else if (userObj){
callback(null,userObj)
} else {
callback(new Error('Some strange thing has happened));
}
});
}
问题是您甚至在查询完成之前就返回了 foundUser object
。这就是为什么您将查询对象作为响应而不是文档对象的原因。
有错误的代码
`
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = 函数 findUser(电子邮件){
const foundUser = User.findOne({email: email}, function(err, userObj){
if(err){
return err
} else if (userObj){
return userObj
} else{
return null
}
})
return foundUser
}
`
代码没有错误
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = 函数 findUser(电子邮件){
const foundUser = User.findOne({email: email}, function(err, userObj){
if(err){
return err
} else if (userObj){
return userObj
} else{
return null
}
})
}
只要修改你已有的就可以了...
{
...
return foundUser.toJSON();
}
这将 return 实际 document/value(没有查询的元数据)。
我正在尝试 运行 我的数据库中的一个 mongoose.findOne 但我得到了意外 results.My 查询是
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = function findUser(email){
const foundUser = User.findOne({email: email}, function(err, userObj){
if(err){
return err
} else if (userObj){
return userObj
} else{
return null
}
})
return foundUser
}
但是这个 returns 以下数据(看似随机?)并且有 none 我请求的数据
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: null,
opts: { bufferCommands: true, capped: false },
name: 'users',
collectionName: 'users',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'ds113938.mlab.com',
port: 13938,
user: 'root',
pass: 'root',
name: 'users',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] },
queue: [],
buffer: true,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
model:
{ [Function: model]
hooks: Kareem { _pres: {}, _posts: {} },
base:
Mongoose {
connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'User',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'ds113938.mlab.com',
port: 13938,
user: 'root',
pass: 'root',
name: 'users',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] },
discriminators: undefined,
schema:
Schema {
obj: [Object],
paths: [Object],
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [Object],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: [Object],
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
insertMany: [Function] },
schema:
Schema {
obj:
{ name: [Function: String],
email: [Function: String],
passwordHash: [Function: String],
validation: [Function: String],
validationCode: [Function: String],
favorites: [Function: Array] },
paths:
{ name: [Object],
email: [Object],
passwordHash: [Object],
validation: [Object],
validationCode: [Object],
favorites: [Object],
_id: [Object],
__v: [Object] },
subpaths: {},
virtuals: { id: [Object] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [ [Object], [Object], [Object], [Object] ],
_indexes: [],
methods: {},
statics: {},
tree:
{ name: [Function: String],
email: [Function: String],
passwordHash: [Function: String],
validation: [Function: String],
validationCode: [Function: String],
favorites: [Function: Array],
_id: [Object],
id: [Object],
__v: [Function: Number] },
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
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: 'findOne',
options: { retainKeyOrder: false },
_conditions: { email: 'Adam@gmail.com' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
NodeCollection {
collection:
NativeCollection {
collection: null,
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Object],
queue: [],
buffer: true,
emitter: [Object] },
collectionName: 'users' },
_traceFunction: undefined,
_castError: null,
_count: [Function],
_execUpdate: [Function],
_find: [Function],
_findOne: [Function],
_findOneAndRemove: [Function],
_findOneAndUpdate: [Function] }
我想知道如何解决这个问题,这似乎是我尝试 运行 的查询的概述,而不是所述查询
的结果试试这个:
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = function findUser(email, callback){
User.findOne({email: email}, function(err, userObj){
if(err){
return callback(err);
} else if (userObj){
return callback(null,userObj);
} else {
return callback();
}
});
}
当您执行 User.findOne 时,猫鼬会在回调中调用 mongodb 和 return 您的用户(findOne 函数中的最后一个参数),因此 return发现用户调用回调。
要调用findUser
函数,你需要传递一个回调函数,像这样:
findUser('adam@gmail.com', function(error, userFound) {
console.log(userFound);
});
您可以找到有关 Mongoose findOne 的更多详细信息here and to learn about callback functions you can take a look here
您看到的是 return foundUser
的结果,一个 Mongoose 查询对象。
您正在混合同步和异步代码,您必须等待查询执行并回调调用它的函数,如下所示:
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array });
exports.findUser = function findUser(email,callback){
const foundUser = User.findOne({email: email}, (err, userObj)=>{
if(err){
callback(err)
} else if (userObj){
callback(null,userObj)
} else {
callback(new Error('Some strange thing has happened));
}
});
}
然后您可以这样调用您的函数:
findUser((err,user)=>{
if(err) console.log(err);
console.log(user)
});
为了快速介绍回调,这是从 What is a callback function?
开始的 link我最近遇到了同样的问题。
在我的例子中,在运行之前提出了一个解决方案,尽管在这种情况下该方法必须是异步的。
如下:
async findUser(email,callback){
const foundUser = await User.findOne({email: email}, (err, userObj)=>{
if(err){
callback(err)
} else if (userObj){
callback(null,userObj)
} else {
callback(new Error('Some strange thing has happened));
}
});
}
问题是您甚至在查询完成之前就返回了 foundUser object
。这就是为什么您将查询对象作为响应而不是文档对象的原因。
有错误的代码 ` const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = 函数 findUser(电子邮件){
const foundUser = User.findOne({email: email}, function(err, userObj){
if(err){
return err
} else if (userObj){
return userObj
} else{
return null
}
})
return foundUser
} `
代码没有错误 const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = 函数 findUser(电子邮件){
const foundUser = User.findOne({email: email}, function(err, userObj){
if(err){
return err
} else if (userObj){
return userObj
} else{
return null
}
})
}
只要修改你已有的就可以了...
{
...
return foundUser.toJSON();
}
这将 return 实际 document/value(没有查询的元数据)。