如何使用NODE.js和Express将MongoDB数据发布到嵌套数组

时间:2020-08-23 09:07:40

标签: node.js mongodb express

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

router.post()方法

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中,但我不知道如何将其嵌套在特定用户下。

应该是这样的:

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的新手,所以我无法做到这一点< / p>

角度代码

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

1 个答案:

答案 0 :(得分:0)

您可以在猫鼬中使用Model.prototype.update来更新子文档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,但可以获取更新的根文档-

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