2016-10-01 118 views
1

我有一個用戶模型和一個日誌模型。日誌模型是用戶模型的子文檔。所以在我的用戶模型,我有:貓鼬 - 插入子文檔

var mongoose = require('mongoose'); 
var Log = require('../models/log'); 

var UserSchema = new mongoose.Schema({ 
username: { 
    type: String, 
    unique: true 
}, 
logsHeld: [ 
    Log 
] 
}); 

然後在我的「登錄」模式,我有:

var mongoose = require('mongoose'); 
var logSchema = new mongoose.Schema({ 
    logComment: { 
     type: String, 
    }, 
}); 

module.exports = mongoose.model('Log', logSchema); 

所以在創建一個「用戶」中,「logsHeld」總是從空。我想知道如何將子文檔添加到此用戶模型。

我試着這樣做POST方法:

router.post('/createNewLog', function(req, res) { 
    var user = new User ({ 
      logssHeld: [{ 
       logComment: req.body.logComment 
      }] 
     }); 
      user.save(function(err) { 
       if(err) { 
       req.flash('error', 'Log was not added due to error'); 
       return res.redirect('/home'); 
      } else { 
       req.flash('success', 'Log was successfully added!'); 
       return res.redirect('/home'); 
      } 
     }); 
    }); 

但是,這是行不通的。它還包括一個'新用戶'行,我不認爲我需要這個用戶是現有的

回答

1

您需要使用logSchema而不是Log模型作爲User模型中的子文檔架構。您可以按如下方式訪問模式:

var mongoose = require('mongoose'); 
/* access the Log schema via its Model.schema property */ 
var LogSchema = require('../models/log').schema; // <-- access the schema with this 

var UserSchema = new mongoose.Schema({ 
    username: { 
     type: String, 
     unique: true 
    }, 
    logsHeld: [LogSchema] 
}); 

從另一個答案你的意見,你所面臨的另一個問題

WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error index: testDB.users.$email_1 dup key:

你得到這個,因爲有已經在文檔拿起你的users集合在email字段中最可能具有null值。儘管您的架構沒有明確指定email字段,但您可能在users.email上有一個現有的舊且未使用的唯一索引。

您可以

testDB.users.getIndexes() 

證實了這一點。如果是這樣的話,並手動

testDB.users.dropIndex(<index_name_as_specified_above>) 

刪除不需要的指標並進行與POST,看看是否已經糾正了錯誤,我敢打賭,我的0.02美元是您的users收藏中存在一箇舊的未使用的唯一索引,這是主要問題。

+1

這樣做了,謝謝! – MonkeyOnARock

0

嘗試push在陣列中的貓鼬插入項

var user = new User; 
user.logssHeld.push({ 
    logComment: req.body.logComment 
}); 

user.save(function(err, doc) { 
    //DO whatever you want 
}); 

看到的文檔here

+0

剛剛嘗試過;沒有工作:( – MonkeyOnARock

+0

我更新的答案請看看 – abdulbarik

+0

不幸的是,這仍然是行不通的,它產生這個奇怪的錯誤:'TypeError:this._schema.caster.cast不是一個函數' – MonkeyOnARock

1

嘗試使用logSchema它引用僅子文檔模式,Log指../models/的全部內容日誌

var UserSchema = new mongoose.Schema({ 
    username: { 
     type: String, 
     unique: true 
    }, 
    logsHeld: [ 
     logSchema 
    ] 
}); 

文檔:http://mongoosejs.com/docs/subdocs.html

+1

感謝您的建議。這使得我的代碼工作得更好*,因爲在運行代碼時nodejs不再關閉。但它仍然沒有插入文件;我現在得到這個奇怪的重複錯誤:'WriteError({「code」:11000,「index」:0,「errmsg」:「E11000重複鍵錯誤索引:testDB.users。$ email_1 dup鍵:'etc ...這裏說'電子郵件'是重複的,但沒有提交電子郵件(用戶的電子郵件是在此用戶首次創建帳戶時創建的)。 – MonkeyOnARock