我数据库中的一条记录:
{
"_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
答案 0 :(得分:0)
首先连接到数据库
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});
}