mongoose多对一插入

我需要帮忙! 我正在用nodejs和mongo创build一个网站来学习。

我有一个问题,我知道最好的方法来做到这一点。 我有两个集合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); 

当我得到我rest的结果时,我得到了它:

 [ { "_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" } ] 

这我填充到数据库中,我不知道如何插入它,是否有任何方法自动与mongoose这样做,或者我需要自己创build? 我正在testing这个JSON:

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

我需要做一个插入的标签,如果我有ID或不。 我需要创build它还是有办法自动执行它? 我该怎么做呢?

对不起我的英文= x

一般来说,使用mongooseJS在mongo数据库中创build和保存文档是非常简单的(假设你连接到一个数据库):

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

如果您有一个与模式forms相同的对象,则可以将其传递给构造函数,以便使用对象的属性对mongoose文档对象进行播种。 如果对象无效,则在validation或保存时将传递给callback函数的无效错误。

给定你的testing对象和模式:

 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存储为单独的集合,因此在插入新的Code文档之前,您需要获取/创build任何string值的标签。 然后,您可以使用新的标签文档代替代码文档的string值。 这会创build一个asynchronousstream程,您可以使用Promise (在较新的节点版本中提供)进行pipe理。

 // 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); }); 

你可以这样做

 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); } }); } }; 

希望代码正在反映其逻辑本身

用法:

在你find你的Code文件后说aCode

只是打电话

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