问题描述
我有一个函数,试图从MongoDB中的设置集合中获取特定的值。设置集合中设置对象的标记(包含设置值)为{'settings':'settings'}。模式是:
I've got a function, trying to get a specific value from settings collection in MongoDB. The marker for settings object, containing settings values, in settings collection is {'settings':'settings'}. The schema is:
collection:setting
|--object
|--{'settings':'settings'}
|--{'valueA':'valueA'}
|--...
问题是当我第一次查询设置对象时,集合的设置根本不存在。因此,
The problem is when I first time query settings object, the collection 'settings' simply does not exists. So,
exports.getInstruments = function (callback) {
db.collection("settings", function(error, settings) {
settings.find({ "settings" : "settings" }), (function(err, doc) {
callback(doc.instruments);
});
]);
}
只是挂起,不会调用回调。如果收集不存在,我应该返回或未定义,else - doc.instrumens。
just hangs and callback is not invoked. If collection does not exist, I should return "" or undefined, else - doc.instrumens.
推荐答案
除了一些语法问题,主要的问题是 find
传递到您的回调函数,而不是第一个匹配的文档。如果你只需要一个文档,你应该使用 findOne
。
Aside from some syntax problems, the main problem is that find
passes a Cursor
to your callback function, not the first matching document. If you're expecting just one doc, you should use findOne
instead.
>
This should work:
exports.getInstruments = function (callback) {
db.collection("settings", function(error, settings) {
settings.findOne({ "settings" : "settings" }, function(err, doc) {
callback(doc && doc.instruments);
});
});
};
这篇关于NodeJS + Mongo native - 检查查询之前是否存在集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!