2017-07-07 70 views
0

我目前正在開發一個項目,並且堅持將項目插入數據庫中的數組/對象。我想要做的是將「upvoted」帖子的id添加到「User」集合中的數組/列表中,但是,我似乎無法使其工作。Node.JS&Mongoose - 將項目插入到數據庫中的數組中

的代碼爲我的模式如下:

// this is a child scheme/sub-document 
var uvpSchema = new Schema(); 
uvpSchema.add({ 
    post: String 
}); 

var dvpSchema = new Schema(); 
dvpSchema.add({ 
    post: String 
}); 

//main schema 
var userSchema = new Schema({ 
    firstname: { type: String, required: true }, 
    lastname: { type: String, required: true }, 
    username: { type: String, required: true, unique: true }, 
    password: { type: String, required: true }, 
    upVotedPosts: [uvpSchema], 
    downVotedPosts: [dvpSchema], 
    created_at: Date, 
}); 

這裏是代碼在我的「routes.js」插入帖子的ID放入數組:

var newPush = { 
     post: postID // postID is a variable that I have already defined 
    }; 
    User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => { 
     if (err) console.log(err); 
     user.upVotedPosts.push(newPush); 
     User.save; 
     res.redirect(req.get('referer')); 
     console.log(user.upVotedPosts); 
    }); 

我收到我的終端的錯誤是:

{ _id: 595f68b5fadd49105813f8a4 },{ _id: 595f693d3c2c21189004b0a7 },{ _id: 595f70a2df80e0252894551b } 
events.js:163 
     throw er; // Unhandled 'error' event 
    ^

在此先感謝;-)

+0

你爲什麼要做'uvpSchema.add',爲什麼不直接像'new Schema({post:String})'那樣創建模式呢? – Aron

+0

還有哪些不起作用?你是否收到任何錯誤訊息? – Aron

+0

對不起:關於錯誤的更多信息更新。我已經嘗試'uvpSchema.add'和'新模式{...}',但他們都返回相同的錯誤 –

回答

0

Route.js

User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => { 
    if (err) console.log(err); 
    user.upVotedPosts.push(newPush); 
    User.save; 
    res.redirect(req.get('referer')); 
    console.log(user.upVotedPosts); 
}); 

你不需要明確地推,因爲你推使用findOneandUpdate - $推

參考here

其次,它

user.save() 

,而不是

User.save 
+0

感謝您的幫助:-) 不幸的是,我仍然得到同樣的錯誤。 –

+0

嘗試在回調中重定向,刪除user.upvoted.push和user.save –

+0

確保每次更改後都要重新啓動服務器 –

0

首先,我要感謝大家的幫助;-)


我終於設法得到它部分工作!我的問題是我的功能異步運行,導致一些問題。我通過爲每個貓鼬函數添加回調函數來解決這個問題。

但是,同樣的錯誤仍然被返回,導致服務器崩潰。其他一切正常;新項目被添加到數組中。

有無論如何忽略錯誤,使服務器不會崩潰?

相關問題