简体   繁体   中英

How to query mongoDB using mongoose?

How do you query MongoDB using mongoose with node.js? I have it to where I can insert my JSON object to my DB, but all the ways I have tried to return the JSON object from the DB return null or just information about the database.

Is there some good method using mongoose to be able to query the database similar to the method:

var cursor = db.collection.find()
var JSONobject = cursor.next()

Here's what is in my code right now:

mongoose.connect('mongodb://localhost/myDB');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
var cursor = mongoose.connection.db.contents.find();
console.log(cursor.next());

This throws an error at the line :

var cursor = mongoose....

claiming 'cannot call method 'find' of undefined'.

Note, that my collection 'contents' does in fact exist, and it contains one JSON document. I know this because I manually navigated to the collection using the mongo shell.

Edit: I am open to alternative methods to querying the database. I simply just want to be able to return JSON objects from my DB one at a time, while keeping track of where the client is at in the database.

One method to query mongoDB using mongoose is as follows:

Content.findOne().exec(function(err,docs){console.log(docs)});

Docs contains the JSON object. Access its attributes like any other object.

Note, this method uses asynchronous call backs. As such, you can't store the JSON object docs to a variable in order to use the JSON document information outside of the function. Therefore, you need to perform whatever actions needed with the JSON docs object information inside of the function.

For example, I was needing the query information to provide the filepath for my get api. As such, the result was as follows:

//get
app.get('/api/media/', function(req,res){
    Content.findOne().exec(function(err,docs){res.sendFile(path.join(__dirname, '/api/media/', docs.filename))});

});

Note, Content is the model of my schema, and one of its parameters is filename.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM