몽구스 프로미스 사용법 - 몽고
누가 몽구스와 함께 약속을 사용하는 방법에 대해 예를 들어줄 수 있습니까?제가 가진 것은 다음과 같습니다. 하지만 예상대로 작동하지 않습니다.
app.use(function (req, res, next) {
res.local('myStuff', myLib.process(req.path, something));
console.log(res.local('myStuff'));
next();
});
그리고 내 입술에는 다음과 같은 것이 있을 것입니다.
exports.process = function ( r, callback ) {
var promise = new mongoose.Promise;
if(callback) promise.addBack(callback);
Content.find( {route : r }, function (err, docs) {
promise.resolve.bind(promise)(err, docs);
});
return promise;
};
어느 시점에 데이터가 있을 것으로 예상되지만 어떻게 액세스하거나 액세스할 수 있습니까?
현재 버전의 Mongoose에서,exec()
method는 Promise를 반환하므로 다음을 수행할 수 있습니다.
exports.process = function(r) {
return Content.find({route: r}).exec();
}
그런 다음 데이터를 가져오려면 비동기식으로 만들어야 합니다.
app.use(function(req, res, next) {
res.local('myStuff', myLib.process(req.path));
res.local('myStuff')
.then(function(doc) { // <- this is the Promise interface.
console.log(doc);
next();
}, function(err) {
// handle error here.
});
});
약속에 대한 더 많은 정보를 위해, 제가 최근에 읽은 멋진 기사가 있습니다: http://spion.github.io/posts/why-i-am-switching-to-promises.html
몽구스는 당신이 전화할 때 이미 약속을 사용합니다.exec()
문의에 의하여
var promise = Content.find( {route : r }).exec();
Mongoose 4.0은 브라우저의 스키마 유효성 검사, 미들웨어 쿼리, 업데이트 시 유효성 검사 및 비동기 작업 약속과 같은 몇 가지 흥미로운 새로운 기능을 제공합니다.
mongoose@4.1을 사용하면 원하는 모든 약속을 사용할 수 있습니다.
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
폴리필 글로벌을 사용하는 또 다른 예입니다.약속.
require('es6-promise').polyfill();
var mongoose = require('mongoose');
그러니까, 그냥 나중에 해도 됩니다.
Content
.find({route : r})
.then(function(docs) {}, function(err) {});
또는
Content
.find({route : r})
.then(function(docs) {})
.catch(function(err) {});
Mongoose 5.0은 기본적으로 기본 약속을 사용합니다. 그렇지 않으면 약속이 없습니다.다음을 사용하여 사용자 지정 약속 라이브러리를 설정할 수 있습니다.
mongoose.Promise = require('bluebird');
그러나 약속은 지원되지 않습니다.
당신이 찾고 있는 것은
exports.process = function ( r, callback ) {
var promise = new mongoose.Promise;
if(callback) promise.addBack(callback);
Content.find( {route : r }, function (err, docs) {
if(err) {
promise.error(err);
return;
}
promise.complete(docs);
});
return promise;
};
다음 페이지:http://mongoosejs.com/docs/promises.html
제목은 플러그 인 나만의 약속 라이브러리입니다.
Bluebird Promise 라이브러리를 다음과 같이 사용합니다.
var Promise = require('bluebird');
var mongoose = require('mongoose');
var mongoose = Promise.promisifyAll(mongoose);
User.findAsync({}).then(function(users){
console.log(users)
})
이 기능은 다음과 같은 기능을 참조하십시오.
User.findAsync({}).then(function(users){
console.log(users)
}).then(function(){
// more async stuff
})
언급URL : https://stackoverflow.com/questions/9022099/how-to-use-mongoose-promise-mongo
'code' 카테고리의 다른 글
MongoDB에서 OneOverfindOneAndUpdate를 통한 업데이트 사용 사례 (0) | 2023.05.23 |
---|---|
Mongo ObjectId를 직렬화하는 동안 JSON.NET 캐스트 오류가 발생했습니다. (0) | 2023.05.23 |
Git의 디렉터리에 있는 파일을 어떻게 무시합니까? (0) | 2023.05.23 |
응용 프로그램이 실행되는 실행 파일 디렉터리? (0) | 2023.05.18 |
VB.NET 및 C#의 값에 대해 null을 확인하는 데 차이가 있는 이유는 무엇입니까? (0) | 2023.05.18 |