如何从MongoDB返回数据 [英] How to return data from MongoDB
问题描述
我正在尝试使用Mongoose查询我的MongoDB数据库。我正在使用findOne按object_id进行搜索,目的是从相应的对象返回start和end字段。但是,我没有将两条消息中的一条记录到控制台,而是未定义。我的模式,我的Events集合中的示例对象和查询代码如下:
I'm attempting to query my MongoDB database using Mongoose. I'm using findOne to search by object_id and aiming to return the "start" and "end" fields from the corresponding object. However, instead of getting one of the two messages logged to the console I get 'undefined'. My schema, example object from my Events collection, and query code are below:
Mongoose模式:
Mongoose Schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var eventSchema = new Schema({
event: String,
city: String,
state: String,
date: String,
start: String,
end: Number,
radius: String,
team_1: String,
team_2: String,
object_id: String,
photos: []
})
module.exports = mongoose.model('Event', eventSchema);
来自MongoDB的示例对象事件集合:
Example object from MongoDB Event collection:
{
"_id": {
"$oid": "5495d1e2ac1e3caaeee84483"
},
"event": "Rockefeller Center",
"city": "New York",
"state": "New York",
"date": "",
"start": "December 18, 2014",
"end": "January 2, 2015",
"radius": "40",
"team_1": "",
"team_2": "",
"object_id": "10881503",
"photos": []
}
服务器代码:
//loop through incoming API POSTS. object_id is guaranteed to be in 'data'
req.body.forEach(function (data) {
var result = Event.findOne(
{object_id: data.object_id},
{ start: 1, end: 1 }
);
if (result) {
var startDate = result.start;
console.log(startDate);
} else {
console.log('object_id not found');
}
});
推荐答案
Mongoose为MongoDB提供了一个异步接口,所以 findOne
不返回找到的文档,它将它传递给你提供的另一个参数的回调函数。
Mongoose provides an asynchronous interface to MongoDB, so findOne
doesn't return the found doc, it passes it to a callback function that you provide as another parameter.
req.body.forEach(function (data) {
Event.findOne(
{object_id: data.object_id},
{ start: 1, end: 1 },
function(err, result) {
if (result) {
var startDate = result.start;
console.log(startDate);
} else {
console.log('object_id not found');
}
}
);
});
这篇关于如何从MongoDB返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!