我正在尝试使用 Mongoose 查询我的 MongoDB 数据库。我正在使用 findOne 按 object_id 进行搜索,目的是从相应的对象返回“开始”和“结束”字段。但是,我没有将两条消息之一记录到控制台,而是得到“未定义”。我的模式、我的事件集合中的示例对象和查询代码如下:
Mongoose 模式:
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 事件集合的示例对象:
{
"_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 提供异步接口(interface),因此 findOne
不会返回找到的文档,而是将其传递给您作为另一个参数提供的回调函数。
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');
}
}
);
});
关于javascript - 如何从 MongoDB 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27595602/