【问题标题】:Node.JS & Mongoose - insert item into an array in the databaseNode.JS 和 Mongoose - 将项目插入数据库中的数组
【发布时间】: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


【解决方案1】:

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

参考here

其次,它的

user.save() 

而不是

User.save

【讨论】:

  • 感谢您的帮助 :-) 不幸的是,我仍然遇到同样的错误。
  • 尝试在回调内部重定向,删除 user.upvoted.push 和 user.save
  • 确保每次更改后都重新启动服务器
【解决方案2】:

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


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

但是,仍然返回相同的错误,导致服务器崩溃。其他一切正常;新项目被添加到数组中。

有没有办法忽略错误以免服务器崩溃?

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多