【发布时间】:2017-07-08 18:34:18
【问题描述】:
我目前正在做一个项目,但我一直坚持将一个项目插入到数据库中的数组/对象中。我想要做的是将“upvoted”帖子的 id 添加到“用户”集合中的数组/列表中,但是,我似乎无法让它工作。
我的架构代码如下:
// 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})那样直接创建架构? -
还有什么不起作用?您是否收到任何错误消息?
-
对此感到抱歉:更新了有关错误的更多信息。我已经尝试过 'uvpSchema.add' 和 'new Schema {...}' 但它们都返回相同的错误
-
嗯,这个错误信息量不是很大。没有别的了吗?
-
不,这是我似乎得到的唯一错误。似乎项目的 id 被添加到数组中,而不是项目本身:/
标签: javascript arrays node.js mongodb mongoose