I'm tearing my hair out, trying to write a simple query in MongoDB Application Services, which I believe uses Mongoose in Node.js.
I have a simple collection with Users
, and I'm trying to find
a set of users.
In testing, this prints a single user, as expected:
exports = async function(){
db = context.services.get("mongodb-atlas").db("2021_10_DB");
const user_col = db.collection("Users");
alarmingSubjs = await user_col.findOne();
console.log(JSON.stringify(alarmingSubjs));
return "Done";
}
====== log ======
> ran at 1672322424787
> took 691.479418ms
> logs:
{"_id":"61807c0fd8c5df7ff5d09571",...} <----- prints entire document for a single user
> result:
"Done"
> result (JavaScript):
EJSON.parse('"Done"')
but, switching findOne
to find
prints no users, which is not expected. (ref db.collection.find() and querying documents )
exports = async function(){
db = context.services.get("mongodb-atlas").db("2021_10_DB");
const user_col = db.collection("Users");
alarmingSubjs = await user_col.find();
console.log(JSON.stringify(alarmingSubjs));
return "Done";
}
====== log ======
> ran at 1672322583386
> took 443.279884ms
> logs:
{} <------ no documents
> result:
"Done"
> result (JavaScript):
EJSON.parse('"Done"')
I tried:
async
and await
, this makes both find
and findOne
return an empty objectfind
, which is not discussed in the documentation that I found, but is discussed in a few stack overflow questions ( example ), doing this:// tried this
db.collection("Users").find({}, (err, user) => {
console.log(JSON.stringify(user));
});
//and this
db.collection("Users").find({}, (err, user) => {
console.log(user);
});
both result in
> ran at 1672323629660
> took 273.490161ms
> result:
"Done"
> result (JavaScript):
EJSON.parse('"Done"')
runCommand
but I get TypeError: 'runCommand' is not a function
This does not look like Mongoose, it looks like the regular Node.js Mongo driver.
Which would return a cursor object from find()
, as shown in the documentation here .
Please try
alarmingSubjs = await user_col.find().toArray();
Which would enumerate the cursor and return an array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.