在此先感谢您的帮助,非常感谢!
我在一个新项目中使用Node.js,MongoDB和Mongoose,我只是想在数据库中find()
文档。为了简洁起见,我将在下面添加Mongoose代码(我现在做的不仅仅是这个):
var mongoose = require('mongoose');
mongoose.connect('mongodb://<username>:<password>@<sub-domain>.mongolab.com:<port>/<db>');
var schema = { email_address: String, invite: String }
, Users = mongoose.model('Users', new mongoose.Schema(schema));
console.log(Users.findOne({ 'email_address': 'jonathon@foo.bar' }, function(err, doc) { return doc; }));
我很确定应该将返回的doc
回显到Node.js控制台(终端),而是我得到了这个:
{ options: { populate: {} },
safe: undefined,
_conditions: { email_address: 'jonathon@foo.bar' },
_updateArg: {},
_fields: undefined,
op: 'findOne',
model:
{ [Function: model]
modelName: 'Users',
model: [Function: model],
options: undefined,
db:
{ base: [Object],
collections: [Object],
models: {},
replica: false,
hosts: null,
host: '<sub-domain>.mongolab.com',
port: <port>,
user: '<username>',
pass: '<password>',
name: '<db>',
options: [Object],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
db: [Object] },
schema:
{ paths: [Object],
subpaths: {},
virtuals: [Object],
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
options: [Object] },
collection:
{ collection: null,
name: 'users',
conn: [Object],
buffer: true,
queue: [Object],
opts: {} },
base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: {},
Collection: [Function: NativeCollection],
Connection: [Function: NativeConnection],
version: '3.5.4',
Mongoose: [Function: Mongoose],
Schema: [Object],
SchemaType: [Object],
SchemaTypes: [Object],
VirtualType: [Function: VirtualType],
Types: [Object],
Query: [Object],
Promise: [Function: Promise],
Model: [Object],
Document: [Object],
Error: [Object],
mongo: [Object] } } }
显然我只是使用<username>
位模糊了我的真实凭证,它们在我的代码中都是正确的。
数据库中确实有一个符合条件的文档,但即使从findOne
方法中删除条件也不会产生任何结果!
我对Node.js相当新,所以我可以解释一下你的答案,所以我知道下次这将是一个很好的帮助!谢谢!
答案 0 :(得分:4)
将您的代码更改为:
Users.findOne({ 'email_address': 'jonathon@foo.bar' }, function(err, doc) {
console.log(doc);
});
我无法从您的代码中看到,但我认为您正在将mongoose函数的值写入控制台......
答案 1 :(得分:2)
我完全忘了,Node.js是异步的,所以行console.log(Users.findOne({ 'email_address': 'jonathon@foo.bar' }, function(err, doc) { return doc; }));
确实回显到控制台,虽然数据库还没有返回任何文件!
相反,console.log
方法应该在find
的回调中,la:
Users.find({}, function(err, doc) { console.log(doc); });