簡體   English   中英

使用 mongoose 更新 mongoDB 中的子文檔

[英]Update a subdocument in mongoDB using mongoose

用戶模式

import mongoose, { Schema, model } from 'mongoose';

const TodoSchema = new Schema({
    task: {
        type: String,
        required: [true, 'Task is required'],
    },
    date: {
        type: Date,
        default: Date.now,
    },
    tags: {
        type: [String],
    },
});

const UserSchema = new Schema({
    name: String,
    googleId: Number,
    date: { type: Date, default: Date.now },
    email: String,
    picture: String,
    todos: {
        type: [TodoSchema],
    },
});
  1. 使用(一些) googleId查詢用戶
  2. 查找嵌入在todos數組中的 (todo) _id的 todo
  3. 更新該 todo 屬性並返回新的 todo。

我的方法

const user = await User.findOne({ googleId });
const { todos } = user;

const idx = todos.findIndex((td) => td._id == todoId);

todos[idx].task = task;
todos[idx].tags = tags;

const { todos: updatedTodos } = await user.save();

我的方法有問題

我的方法確實有效,但它似乎不是一個最佳解決方案,就像在 todo 模式中更改或添加更多字段的情況一樣。 雖然我確實考慮過使用擴展運算符,但是每次更新 todo 時都會產生新的 todo id

問題

我應該如何使用 mongoose 做到這一點?

如果你有 todos 的 Schema,這意味着每個 todo 在 MongoDB 中都有一個唯一的 id。 您不必在步驟 2 中過濾待辦事項:

STEP 1:
const user = await User.findOne({ googleId });
const { todos } = user;

STEP 2: // don't do this
const idx = todos.findIndex((td) => td._id == todoId);

STEP 3:
todos[idx].task = task;
todos[idx].tags = tags;

STEP 4:
const { todos: updatedTodos } = await user.save();

考慮一下:

  • 您已經有了要修改的 todoId
  • 查找用戶是否存在
  • 檢查待辦事項是否屬於用戶
  • findByIdAndUpdate下使用 findByIdAndUpdate

我的建議:

const todoId = xxxxxxxxx

const user = await User.findOne({googleId})

const orderIdBelongsToUser = user.todos.includes(todoId)
// I'm assuming this is an array of orderIds, otherwise you can decide whether or not to do this check. 
// It seems pretty redundant, if you already have the todo id.

const newTodoObject = {
task: xxxx,
tags: xxxxx
}

if (orderIdBelongsToUser) {
const response = await Todo.findByIdAndUpdate(todoId, newTodoObject)
}

希望我能提供幫助。

參考: https://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM