简体   繁体   English

如何使用猫鼬查询mongoDB?

[英]How to query mongoDB using mongoose?

How do you query MongoDB using mongoose with node.js? 如何使用mongoose和node.js查询MongoDB? 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. 我拥有将JSON对象插入数据库的位置,但是尝试从数据库返回JSON对象的所有方法都返回null或仅返回有关数据库的信息。

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. 请注意,我的集合“内容”确实存在,并且包含一个JSON文档。 I know this because I manually navigated to the collection using the mongo shell. 我知道这一点是因为我使用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. 我只希望能够一次从数据库中返回一个JSON对象,同时跟踪客户端在数据库中的位置。

One method to query mongoDB using mongoose is as follows: 一种使用猫鼬查询mongoDB的方法如下:

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

Docs contains the JSON object. 文档包含JSON对象。 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. 因此,您无法将JSON对象文档存储到变量中,以便在函数外部使用JSON文档信息。 Therefore, you need to perform whatever actions needed with the JSON docs object information inside of the function. 因此,您需要对函数内部的JSON文档对象信息执行所需的任何操作。

For example, I was needing the query information to provide the filepath for my get api. 例如,我需要查询信息来为我的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. 注意,内容是我的架构的模型,其参数之一是文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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