Javascript Node.JS&;Mongoose-将项插入数据库中的数组中

Javascript Node.JS&;Mongoose-将项插入数据库中的数组中,javascript,arrays,node.js,mongodb,mongoose,Javascript,Arrays,Node.js,Mongodb,Mongoose,我目前正在处理一个项目,我一直在将项目插入数据库中的数组/对象。我试图做的是将一篇“被投票”的文章的id添加到“用户”集合中的数组/列表中,但是,我似乎无法让它工作 我的模式的代码如下所示: // this is a child scheme/sub-document var uvpSchema = new Schema(); uvpSchema.add({ post: String }); var dvpSchema = new Schema(); dvpSchema.add({ p

我目前正在处理一个项目,我一直在将项目插入数据库中的数组/对象。我试图做的是将一篇“被投票”的文章的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
      ^
提前感谢;-)

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-$push推送

提及

第二,它的

user.save() 
而不是

User.save

首先,我要感谢大家的帮助;-)


我终于设法让它部分工作了!我的问题是我的函数异步运行,导致了一些问题。我通过向每个mongoose函数添加回调函数来解决这个问题

但是,仍然返回相同的错误,导致服务器崩溃。其他一切都起作用;新项将添加到数组中


还有什么方法可以忽略错误,这样服务器就不会崩溃吗?

为什么要执行
uvpSchema.add
,为什么不直接像
newschema({post:String})
那样创建模式呢?还有什么方法不起作用?您是否收到任何错误消息?很抱歉:已更新有关错误的更多信息。我尝试了“uvpSchema.add”和“new Schema{…}”,但它们都返回相同的错误。这个错误信息量不大。没有别的了吗?没有,这是我唯一的错误。似乎正在将项的id添加到数组中,而不是项本身:/Thank you to help:-)很遗憾,我仍然收到相同的错误。请尝试在回调中重定向,删除user.upvoted.push和user.save确保每次更改后都重新启动服务器