2015-04-30 111 views
1

我需要幫忙! 我正在創建一個帶有nodejs和mongo的網站供學習。貓鼬多對一插入

我有一個問題,我知道最好的方法來做到這一點。 我有兩個系列codestag進入表codes我有tags字段是tags的數組。

CodeModel:

var CodeSchema = new Schema({ 
    title: { type: 'String', required: true }, 
    text: { type: 'String', required: true }, 
    url: { type: 'String', required: true }, 
    uri: String, 

    createdAt: { type: Date, default: Date.now }, 
    updatedAt: { type: Date, default: Date.now }, 

    owner: { 
     type: Schema.ObjectId, 
     ref: 'User' 
    }, 

    tags: [ 
     { 
      type: Schema.ObjectId, 
      ref: 'Tag' 
     } 
    ] 

}); 

CodeSchema.pre("save", function (next) { 
    // if create for first time 
    if (!this.created_at) { 
     this.created_at = Date.now(); 
    } 

    next(); 
}); 

module.exports = mongoose.model('Code', CodeSchema); 

和我的標籤型號:

var mongoose  = require('mongoose'); 
var Schema  = mongoose.Schema; 

var TagSchema = new Schema({ 
    name: 'string' 
}); 

module.exports = mongoose.model('Tag', TagSchema); 

,當我得到的結果在我休息我懂了:

[ 
    { 
    "_id": "5540f557bda6c4c5559ef638", 
    "owner": { 
     "_id": "5540bf62ebe5874a1b223166", 
     "token": "7db8a4e1ba11d8dc04b199faddde6a250eb8a104a651823e7e4cc296a3768be6" 
    }, 
    "uri": "test-save", 
    "url": "http://www.google.com.br/", 
    "text": " hello ", 
    "title": "testing...", 
    "__v": 0, 
    "tags": [ 
     { 
     "_id": "55411700423d29c70c30a8f8", 
     "name": "GO" 
     }, 
     { 
     "_id": "55411723fe083218869a82d1", 
     "name": "JAVA" 
     } 
    ], 
    "updatedAt": "2015-04-29T15:14:31.579Z", 
    "createdAt": "2015-04-29T15:14:31.579Z" 
    } 
] 

這我填充到數據庫中,我不知道我是如何插入它的,是否有任何方法自動與貓鼬那樣做,或者我需要自己創建? 我與此JSON測試:

{ 
    "url": "http://www.google.com.br/", 
    "title": "Test inset", 
    "text": "insert code", 
    "tags": [ 
    "ANGULAR", 
    { 
     "_id": "55411700423d29c70c30a8f8", 
     "name": "GO" 
    } 
    ] 
} 

我需要做的標籤一插入,如果我有身份證或沒有。我需要創建它還是有辦法自動完成它? 我該怎麼做?

對不起我的英語= X

回答

1

一般而言,創建並保存在文檔中使用mongooseJS一個蒙戈數據庫是相當簡單的(假設你連接到數據庫):

var localDocObj = SomeSchemaModel(OPTIONAL_OBJ); // localDocObj is a mongoose document 
localDocObj.save(CALLBACK); // save the local mongoose document to mongo 

如果你有一個對象,與模式具有相同的形式,您可以將其傳遞給構造函數,以便使用對象的屬性對貓鼬文檔對象進行播種。如果該對象無效,則在驗證或保存時將傳遞給回調函數的失效錯誤。

由於測試對象和模式:

var testObj = { 
    "url": "http://www.google.com.br/", 
    "title": "Test inset", 
    "text": "insert code", 
    "tags": [ 
    "ANGULAR", 
    { 
     "_id": "55411700423d29c70c30a8f8", 
     "name": "GO" 
    } 
    ] 
}; 

var codeDoc = Code(testObj); 
codeDoc.save(function (err, doc) { 
    console.log(err); // will show the invalidation error for the tag 'Angular' 
}); 

既然你存儲Tag作爲一個單獨的集合,您將需要獲取/插入新代碼文檔之前創建的字符串值的任何標記。然後,您可以使用新的標籤文檔代替代碼文檔的字符串值。這會創建一個異步流程,您可以使用Promises(在較新的節點版本中提供)進行管理。

// Create a promise for all items in the tags array to iterate over 
// and resolve for creating a new Code document 
var promise = Promise.all(testObj.tags.map(function(tag) { 
    if (typeof tag === 'object') { 
    // Assuming it exists in mongo already 
    return tag; 
    } 

    // See if a tag already exists 
    return Tag.findOne({ 
    name: tag 
    }).exec().then(function(doc) { 
    if (doc) { return doc; } 

    // if no tag exists, create one 
    return (Tag({ 
     name: tag 
    })).save(); // returns a promise 
    }); 
})).then(function(tags) { 
    // All tags were checked and fetched/created if not an object 
    // Update tags array 
    testObj.tags = tags; 

    // Finally add Code document 
    var code = Code(testObj); 
    return code.save(); 
}).then(function(code) { 
    // code is the returned mongo document 
    console.log(code); 
}).catch(function(err) { 
    // error in one of the promises 
    console.log(err); 
}); 
+0

謝謝你,我做到了,它完美無缺。我正在學習,我還有一些簡單的問題,但我明白了。 –

0

你可以不喜歡它

var checkNewTagAndSave = function(data, doc, next){ // data = req.body (your input json), doc = mongoose document to be saved, next is the callback 
    var updateNow = function(toSave, newTags){ 
     // save your mongoose doc and call the callback. 
     doc.set(toSave); 
     doc.save(next); 
    }; 
    var data = req.body; 
    var tagsToCreate = []; 
    var tagids = []; 
    data.tags.forEach(function(tag, index){ 
     if(typeof(tag) == 'string') { 
     tagsToCreate.push({ name: tag }); 
     } else tagids.push(tag._id); 
    }); 
    data.tags = tagids; 
    if(tagsToCreate.length === 0) updateNow(data); 
    else { 
     mongoose.model('tag').create(tagsToCreate, function(err, models){ 
     if(err || !models) return next(err); 
     else { 
      models.forEach(function(model){ 
      data.tags.push(model._id); 
      }); 
      updateNow(data, models); 
     } 
     }); 
    } 
}; 

希望代碼以反映其邏輯本身

用法:

你發現後您的Code文件說aCode

只調用

checkNewTagAndSave(req.body, aCode, function(err, doc){ 
    //end your response as per logic 
}); 
+0

感謝您的幫助。 –