如何使用 NODE.js 和 Express 将 MongoDB 数据发布到嵌套数组 [英] How to post MongoDB data to the nested array using NODE.js and Express

查看:47
本文介绍了如何使用 NODE.js 和 Express 将 MongoDB 数据发布到嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将数据从 MongoDB 发布给登录的用户.因此,每当用户触发发布数据的请求时,它都应该发送并嵌套在该用户下.

I have been trying to post data from MongoDB to the user that is logged in. So whenever a user triggers a request to post data it should be sent and nested under that user.

router.post() 方法

router.post() method

router.post('/savetasks', async (req, res) => {
  console.log(req.body);
  const { startTime, endTime, elapsedTime } = req.body;
  const newTime = new Time({startTime, endTime, elapsedTime});
  await newTime.save();

  const token = jwt.sign({ _id: newTime._id}, 'secretkey');

  res.status(200).json({token}); 

});

使用这种方法我可以成功地将数据保存在 MongoDB 中,但我不明白如何将其嵌套在特定用户下.

Using this method I can successfully save data in MongoDB but I don't understand how to get it nested under the specific user.

应该是这样的:

const userSchema = new Schema({
firstname: String,
lastname: String,
email: String,
password: String,
timings: [{
    startTime: String,
    endTime: String,
    elapsedTime: String
}]
});

我尝试了不同的方法,但所有方法都给我错误.给我最大信心的一种方法实际上是提供路径/posttasks/:_id",并分配 add.function() 但因为我是 Mongo、Express 和 Node.js 的新手我无法做到这一点

I have tried different ways but all of them were giving me errors. The one way that gives me the most faith is actually with giving path '/posttasks/:_id', and assigning add.function() but since I am new in Mongo, Express, and Node.js I couldn't accomplish that

角度代码

import { Component, OnInit } from '@angular/core';
import { timer, from } from 'rxjs';
import { AuthService} from '../../services/auth.service';
import { TasksService } from '../../services/tasks.service';
import * as moment from 'moment';
import {formatDate} from '@angular/common';
import { Router } from '@angular/router';


@Component({
 selector: 'app-private-tasks',
templateUrl: './private-tasks.component.html',
styleUrls: ['./private-tasks.component.css']
})
export class PrivateTasksComponent implements OnInit {

date:Date; 

times: number = 0;
display ;
interval;

time = [] as any;

tasks = [] as any;
user = [] as any;

startTime: any = formatDate(new Date(), 'yyyy/MM/dd HH:mm:ss', 'en');
endTime: any= formatDate(new Date(), 'yyyy/MM/dd HH:mm:ss', 'en');
elapsedTime: any = formatDate(new Date(), 'HH:mm:ss', 'en'); 

constructor(
  private authService: AuthService,
  private tasksService: TasksService,
  private router: Router
) {

setInterval(() => {
  this.date = new Date()
}, 1000)
}




ngOnInit(): void {
  this.tasksService.getTasks1()
    .subscribe(
      res => {
        this.tasks = res; 
        console.log(this.tasks);
        
                   
      },
      err => console.log(err)
   );
}


startTimer() {  
  console.log("=====>");
  this.startTime = new Date();
  this.interval = setInterval(() => {
    if (this.times === 0) {
      console.log(this.startTime);
      this.times++;
    } else {
      this.times++;
    }
    this.display=this.transform( this.times)
  }, 1000);
}
transform(value: number) {
   var minutes: number =  Math.floor(value / 60);
   var hours : number = Math.floor(minutes / 60);
   return hours + ':' + minutes;
}

pauseTimer() {
  clearInterval(this.interval);

  this.endTime = new Date();
  //this.userID = new this.userID;
  console.log(this.endTime);

  const requestBody = {
    startTime: this.startTime,
    endTime: this.endTime,
    elapsedTime: this.endTime - this.startTime
};

  this.authService.postTasks({ requestBody })
    .subscribe(
      res => {
        this.time = res;
        console.log(this.time);
      },
      err => console.log(err)
    );
}
}

推荐答案

您可以使用 Model.prototype.update in mongoose 更新子文档timings.

但是存在两种情况-

  1. 如果您想推送条目而不需要检查重复项,请使用 $push 操作符

    var filter = {
        _id: mongoose.Types.ObjectId('<USER_ID>')
    };
    
    var update = {
        $push: {
            timings: {
                startTime: "",
                endTime: "",
                elapsedTime: ""
            }
        }
    };
    
    db.collection.update(filter, update);

  1. 如果您只想推送不同的条目,请使用 $addToSet 运算符

    var filter = {
        _id: mongoose.Types.ObjectId('<USER_ID>')
    };
    
    var update = {
        $addToSet: {
            timings: {
                startTime: "",
                endTime: "",
                elapsedTime: ""
            }
        }
    };
    
    db.collection.update(filter, update);

注意:首先需要mongoose

const mongoose = require('mongoose');


将您的代码更正为以下,您也无法获得确切的子文档的Id,但您可以获得更新的根文档-


Correct your code to the below, also you can't get the exact sub-document's Id, but you can get the updated root document -

const updatedUser = await User.findOneAndUpdate({
        _id: mongoose.Types.ObjectId(req.body._id)
    },
    {
        $addToSet: {
            timings: {
                startTime, 
                endTime, 
                elapsedTime
            }
        }
    }, {
        new: true
    }).exec();

这篇关于如何使用 NODE.js 和 Express 将 MongoDB 数据发布到嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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