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

编程入门 行业动态 更新时间:2024-10-23 07:34:17
本文介绍了如何使用 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-tasksponent.html', styleUrls: ['./private-tasksponent.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.

但是存在两种情况-

  • 如果您想推送条目而不需要检查重复项,请使用 $push 操作符
  • var filter = { _id: mongoose.Types.ObjectId('<USER_ID>') }; var update = { $push: { timings: { startTime: "", endTime: "", elapsedTime: "" } } }; db.collection.update(filter, update);

  • 如果您只想推送不同的条目,请使用 $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 数据发布到嵌套数组

    本文发布于:2023-11-22 19:19:39,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1618684.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:嵌套   数组   如何使用   数据   NODE

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!