随着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