隨着Node.js的驅動程序,使用收集的insert()
方法,它返回一個承諾。下面的例子說明了這一點:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var db = new Db('test', new Server('localhost', 27017));
// Fetch a collection to insert document into
db.open(function(err, db) {
var collection = db.collection("post");
// Create a function to return a promise
function getPostPromise(post){
return collection.insert(post);
}
// Create post to insert
var post = { "title": "This is a test" },
promise = getPostPromise(post); // Get the promise by calling the function
// Use the promise to log the _id
promise.then(function(posts){
console.log("Post added with _id " + posts[0]._id);
}).error(function(error){
console.log(error);
}).finally(function() {
db.close();
});
});
您還可以使用貓鼬的save()
方法,因爲它返回一個Promise
。一個基本的例子來證明這一點如下:
// test.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// Establish a connection
mongoose.connect('mongodb://localhost/test', function(err) {
if (err) { console.log(err) }
});
var postSchema = new Schema({
"title": String
});
mongoose.model('Post', postSchema);
var Post = mongoose.model('Post');
function getPostPromise(postTitle){
var p = new Post();
p.title = postTitle;
return p.save();
}
var promise = getPostPromise("This is a test");
promise.then(function(post){
console.log("Post added with _id " + post._id);
}).error(function(error){
console.log(error);
});
運行程序
$ node test.js
Post added with _id 5696db8a049c1bb2ecaaa10f
$
第一個示例非常完美。謝謝! – Nodal
@Nodal不用擔心,很樂意幫助:) – chridam
嗨,在第一個例子中,我得到一個錯誤,說'TypeError:promise.then(...)。error不是一個函數。我一直無法找到有關此錯誤的更多信息,但我認爲它要麼是缺少使用承諾所需的模塊,要麼是Mongodb中的承諾實現不支持'.error'?或者當然完全是其他的東西。 – Nodal