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

查看:30
本文介绍了通过 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 应用程序,它连接到数据库并使用空的朋友数组成功创建了people".

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
);

我总是尽可能选择第一个选项,因为它会尊重猫鼬给你的更多好处(钩子、验证等).

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天全站免登陆