2016-01-14 73 views
0

我試圖更新包含Document.save()不會對裁判的陣列一起

events: [{type: Schema.Types.ObjectId, ref: 'Event'}]

領域的文件,但每當我執行

user.save(req.body).then(function (user) { 
    res.json(user); 
}); 

user.events未正確保存並保持爲空陣列。

我甚至試着這樣做之前save()

if(req.body.events) 
    req.body.events = req.body.events.map(function(id){ 
     return mongoose.Schema.Types.ObjectId(id); 
    }); 

毫無效果。

回答

0

您在模型中缺少「架構」。 試試這個:

events: [{type: mongoose.Schema.Types.ObjectId, ref: 'Event'}] 

編輯: 有你可能想以檢查,使這項工作一些其他的東西:

(1)確保您獲取您想要的用戶更新。

(2)使用本文檔的該頁面仔細檢查語法。 http://mongoosejs.com/docs/documents.html

它看起來像你的req.body是在一個錯誤的地方。你也不想在這裏使用「.then」。 在你的榜樣,我會把它是這樣的:

User.findById(req.params.id, function(err, user) { 
//Grab the user you want to update from the database. 
    if (err) return handleError(err); 
//This is an extra tip, but use error handlers so you can detect errors. 

    user.events = req.body.events; 
//Here you are updating the user info that you grabbed from the database. 
    user.save(function(err) { 
//Saves the updated user info to the database. 
    if(err) return handleError(err); 
    res.send(user); 
    }); 
}); 

但是,我用「findByIdAndUpdate」或「更新」(均是我所提供的文件鏈接)比上面,因爲它更簡潔。

+0

剛剛嘗試過,也沒有工作。 –