我目前正在開發一個項目,並且堅持將項目插入數據庫中的數組/對象。我想要做的是將「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
^
在此先感謝;-)
個
你爲什麼要做'uvpSchema.add',爲什麼不直接像'new Schema({post:String})'那樣創建模式呢? – Aron
還有哪些不起作用?你是否收到任何錯誤訊息? – Aron
對不起:關於錯誤的更多信息更新。我已經嘗試'uvpSchema.add'和'新模式{...}',但他們都返回相同的錯誤 –