【问题标题】:Push item to array in mlab record array将项目推送到 mlab 记录数组中的数组
【发布时间】:2018-10-10 00:56:36
【问题描述】:

我的数据库中的一条记录:

{
"_id": {
    "$oid": "5b93d84aa9123300043c4f8f"
},
"googleId": "110329027039267241635",
"username": "Carl Junior",
"eoUsers": [
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false
    },
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false
    },
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false
    },
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false,
        earnings: [['1/20', 0.2], ['1/21', 0.1],  // I want to insert item here
    },
     ]]
],
"__v": 0

我想将项目推送到“收益”列表中的数据库,我想我必须使用以下选项之一:https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

但我似乎无法弄清楚。 如何将项目推送到我指定的列表中?


所以插入项目后,记录应该是这样的:

{
"_id": {
    "$oid": "5b93d84aa9123300043c4f8f"
},
"googleId": "110329027039267241635",
"username": "Carl Junior",
"eoUsers": [
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false
    },
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false
    },
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false
    },
    {
        "username": "1@gmail.com",
        "password": "3",
        "loggedIn": false,
         earnings: [['1/20', 0.2], ['1/21', 0.1],  ['I INSERTED', 0.45]]
    },
],
"__v": 0

【问题讨论】:

  • 您想将收入插入到 eoUsers 数组中吗? (或作为它的兄弟姐妹?)
  • 未更新和更新之间的区别正是我想要发生的事情。
  • 您的记录不是有效的 JSON 格式,能否再次检查您的代码?
  • @tashakori 哎呀,对不起。

标签: javascript mlab


【解决方案1】:

首先连接到您的数据库

const mongoose = require('mongoose'); 
mongoose.connect( SPECIAL_KEY , { useNewUrlParser: true });

然后使用我想你已经创建的 userSchema 在你的集合中找到记录。

const User = mongoose.model('user', userSchema);  // where 'user' is the name of your collection

查找记录,例如。 _id,包含要更新的变量

userSchema.findOne({_id: '5b93d84aa9d1a300043c4f8f'})
        .then(OldUserRecord => {
                //Create a new user record, which will be used to overwrite the old
            const newUserRecord_eoUsers = OldUserRecord.eoUsers;
            newUserRecord_eoUsers[3].earnings_log.push( ['value', 0.45] );

                //Update the old user record
            userSchema.update({_id: '5b93d84aa9d1a300043c4f8f'}, {"eoUsers": newUserRecord_eoUsers});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2017-07-10
    • 2011-03-13
    相关资源
    最近更新 更多