在交易中,我没有看到任何访问插入/更新文档密钥的示例。
var collections = {write: ['foo','bar']};
var action = String(function () {
var doc = params['doc'];
var relatedDoc = params['relatedDoc'];
var db = require('internal').db;
db.foo.save(doc); // how do I access the _id, key etc of the newly inserted doc?
relatedDoc.foos.push(doc._id); // _id does not exist yet
db.bar.save(relatedDoc);
return {success: true};
});
var params = {
doc: doc,
relatedDoc: relatedDoc
};
db.transaction(collections, action, params, function (err, result) {
if (err) {
return dfd.reject(err);
}
return dfd.resolve(result);
});
答案 0 :(得分:3)
collection.save()
方法将返回已保存文档的一些元数据:
_rev
:文档修订版ID(由服务器自动生成)_key
:文档密钥(由用户在_key
属性中指定,或者由服务器自动生成,如果没有)_id
:与密钥相同,但也包括集合名称要在代码中使用生成的ID,您可以在变量中捕获collection.save()
的结果,并按如下方式使用它:
var collections = {write: ['foo','bar']};
var action = String(function () {
var doc = params['doc'];
var relatedDoc = params['relatedDoc'];
var db = require('internal').db;
var newDoc = db.foo.save(doc); // capture result of save in newDoc
relatedDoc.foos.push(newDoc._id); // use newDoc._id for
db.bar.save(relatedDoc);
return {success: true};
});
var params = {
doc: doc,
relatedDoc: relatedDoc
};
db.transaction(collections, action, params, function (err, result) {
if (err) {
return dfd.reject(err);
}
return dfd.resolve(result);
});