通过 mongoose 将项目推送到 mongo 数组中 [英] Push items into mongo array via mongoose

查看:16
本文介绍了通过 mongoose 将项目推送到 mongo 数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个名为people"的 mongodb 集合其架构如下:

Basically I have a mongodb collection called 'people' whose schema is as follows:

people: {
         name: String, 
         friends: [{firstName: String, lastName: String}]
        }

现在,我有一个非常基本的 express 应用程序,它连接到数据库并成功地创建了一个带有空朋友数组的人".

Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends array.

在应用程序的次要位置,有一个表单用于添加朋友.该表单接收 firstName 和 lastName,然后使用 name 字段进行 POST,以引用正确的人员对象.

In a secondary place in the application, a form is in place to add friends. The form takes in firstName and lastName and then POSTs with the name field also for reference to the proper people object.

我很难做的是创建一个新朋友对象,然后推".将其放入好友数组中.

What I'm having a hard time doing is creating a new friend object and then "pushing" it into the friends array.

我知道,当我通过 mongo 控制台执行此操作时,我使用带有 $push 的更新函数作为查找条件后的第二个参数,但我似乎找不到合适的方法来让猫鼬这样做.

I know that when I do this via the mongo console I use the update function with $push as my second argument after the lookup criteria, but I can't seem to find the appropriate way to get mongoose to do this.

db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});

推荐答案

假设,var friend = { firstName: 'Harry', lastName: 'Potter' };

您有两种选择:

更新内存中的模型,并保存(纯javascript array.push):

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

我总是尽可能地尝试第一个选项,因为它会尊重 mongoose 为您提供的更多好处(钩子、验证等).

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

但是,如果您正在执行大量并发写入,您将遇到竞争条件,最终会出现严重的版本错误,从而阻止您每次替换整个模型并失去您之前添加的朋友.所以只有在绝对必要时才使用前者.

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

这篇关于通过 mongoose 将项目推送到 mongo 数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆