我试图通过mongoose查询MongoDB而不定义模型。
NoSQLBooster中的此查询将生成正确的结果。
const db = myDB = mongoose.connect(keys.mongoURI, (err, db) => {
myDB = db;
});
db
.then(db => {
connection = mongoose.connection;
console.log('Mongodb has been connected', myDB);
//connection.collection("coins").find({ "serverTime" : { $gt : "1523441870", $lt : "1523441999"}}, function (err, info) {
connection.collection("coins").find({}, function (err, info) {
console.log("info: ", err);
console.log("info: ", info);
});
})
.catch(err => {
console.log('Error while trying to connect with mongodb');
throw err;
});
-
下面的find()将返回数据库中的信息。但它不会从数据库中返回预期的文档。它不会返回任何结果。
Cursor {pool: null, server: null, disconnectHandler: Store, bson: BSON, ns: "dev.coins", …}
index.js:29
_events:Object {}
_eventsCount:0
_maxListeners:undefined
_readableState:ReadableState {objectMode: true, highWaterMark: 16, buffer: BufferList, …}
bson:BSON {}
cmd:Object {find: "dev.coins", limit: 0, skip: 0, …}
cursorState:Object {cursorId: null, cmd: Object, documents: Array(0), …}
destroyed:false
disconnectHandler:Store {s: Object, length: <accessor>}
domain:null
logger:Logger {className: "Cursor"}
namespace:Object
ns:"dev.coins"
options:Object {readPreference: ReadPreference, skip: 0, limit: 0, …}
pool:null
readable:true
readPreference:ReadPreference
s:Object {numberOfRetries: 5, tailableRetryInterval: 500, currentNumberOfRetries: 5, …}
server:null
sortValue:undefined
topology:Server {domain: null, _events: Object, _eventsCount: 23, …}
__proto__:Readable {setCursorBatchSize: , cursorBatchSize: , setCursorLimit: , …}
{{1}}
答案 0 :(得分:0)
首先获得收藏。 处理toArray.then承诺,其中包含您正在寻找的信息。 使用返回的信息循环或执行您想要的操作。
const db = myDB = mongoose.connect(keys.mongoURI, (err, db) => {
myDB = db;
});
db
.then(db => {
connection = mongoose.connection;
let collection = mongoose.connection.db.collection('coins');
console.log('Mongodb has been connected', myDB);
//Find the information
collection.find({ "serverTime" : { $gt : "1523441870", $lt : "1523441999"}}, function (err, info) {
//collection.find({}, function (err, info) {
console.log("info: ", err);
console.log("info: ", info);
//Convert to Array.
//The toArray will return a promise with the info you are looking for.
let array = info.toArray().then(info => {
console.log("more info: ", info[0]["serverTime"]);
});
console.log("info: ", array);
});
})
.catch(err => {
console.log('Error while trying to connect with mongodb');
throw err;
});
答案 1 :(得分:0)
当你在mongoose.connection.collection上调用方法时,实际上是在访问mongodb提供的mongoose依赖的本机驱动程序。 The documentation for that driver exists here
在此上下文中,.find()返回一个cursor,其toArray method接受回调或返回承诺。
您可以将回调从.find()
调用移至.toArray()
来电,如下所示:
connection.collection("coins").find({}).toArray(function (err, info) {
console.log("info: ", err);
console.log("info: ", info);
})
或者你可以实现这样的基于承诺的解决方案:
let results = connection.collection("coins").find({}).toArray()
results.then(console.log).catch(console.error)
请记住,生成的数组将包含整个集合。随着您的集合随着时间的推移而增长,这取决于文档的数量及其大小,这可能导致node.js耗尽堆空间并崩溃。