Array.push 似乎不适用于 MongoDB [英] Array.push does not seem to work on MongoDB

查看:40
本文介绍了Array.push 似乎不适用于 MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 MongoDB 中创建一个动态向量/数组.这个想法很简单:每当有人提交一些东西时,它应该更新我在 MongoDB 中的数据库中的用户.我为此创建了一个变量.我已经测试过:正确找到了正确的用户.

I would like to create a dynamic vector/array in MongoDB. The idea is simple: whenever someone submits something, it should update a user in my database in MongoDB. I have created a variable for that. I have already tested: the proper user is found correctly.

请找出我的代码片段.

User.findOne({ name })
          .then(user => {                
            user.something.push(something to push);
          })

我在创建时设置了默认值:

I have set the default value when it is created as empty:

  something: {   
    type: [String],
    default: []
  }

但是,它不会保存,也不会抛出任何错误.任何人都猜测幕后可能发生的事情?我是 MongoDB 的新手.

However, it does not save, and throw no error. Anyone has a guess of what might be happening behind the scenes? I am new to MongoDB.

推荐答案

您可以使用 findOneAndUpdate() 和 $push mongodb 运算符

You can use findOneAndUpdate() with $push mongodb operator

User.findOneAndUpdate({name:name},{$push:{ something: 'new_data'}});

这篇关于Array.push 似乎不适用于 MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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