我有两个集合,第一个集合包含第二个集合中 id 引用文档的数组。
有一个特定的地方,我想创建一个新的 DocumentType
,然后创建一个引用该 DocumentType
的新 Document
,最后更新原始 DocumentType
来引用新的 Document
。
一个DocumentType
可以有许多Document
,但一个Document
只能有一个DocumentType
。我想在两个地方都有引用的原因是为了简化以后更复杂的查询。
我的问题是:有没有比使用这些多个嵌套回调更好的方法来使用 Mongoose 编写它。
我整理了一个简单的例子来演示。真实事物中有更多数据,因此我不想将 Document
嵌入到 DocumentType
中,反之亦然。
var DocumentTypeSchema = new Schema({
name: String
, desc: String
, documents: [{type: Schema.ObjectId, ref: 'Document'}]
, ...
});
var DocumentSchema = new Schema({
title: String
, doctype: {type: Schema.ObjectId, ref: 'DocumentType'}
, ...
});
var Document = mongoose.model('Document', DocumentSchema);
var DocumentType = mongoose.model('DocumentType', DocumentTypeSchema);
// Begin the nested callbacks
// Create a document type
var type = new DocumentType({...});
// Save document type
type.save(function(err) {
// Create new document
var document = new Document({
doctype: type.id
, ...
});
// Save document
document.save(function(err) {
// Update document type
DocumentType.update({_id: document.doctype}, {'$addToSet': {documents: document.id}}, function(err) {});
});
});
感谢您的帮助
最佳答案
我想说,通常没有更好的同步处理方法。 Jani 提到的 async
库的 series
函数是扁平化这一点的好方法,但我认为坚持使用回调结构通常是一个好主意 - 它使得范围非常清晰,减少了外部依赖——除非嵌套变得荒谬或者你需要异步。你的嵌套并不荒谬,尽管你可能会考虑 async.parallel向前走。如果您要创建两个新实例并在两个实例之间保存属性,则没有理由同步进行创建。相反,像这样:
async.parallel({
type: function(callback) {
var type = new DocumentType({...});
type.save(function(err) {callback(null, type)});
},
document: function(callback) {
var document = new Document({...});
document.save(function(err) {callback(null, document)});
}
},
function(err, results) {
results.document.doctype = results.type.id;
results.document.save();
DocumentType.update(
{_id: results.type},
{'$addToSet': {documents: results.document.id}},
function(err) {}
);
});
它需要额外的保存,坦率地说,对于这样的任务来说可能很愚蠢,性能开销如此之小,但它说明了异步处理的好方法和异步库的多功能性。
关于javascript - Mongoose 保存时可以避免多层嵌套回调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8784169/