node.js - 使用 mongoose 更新 mongoDB 中的子文档
问题描述
用户模式
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],
},
});
- 用(一些)查询用户
googleId
_id
查找嵌入在todos
数组中的 (todo) 待办事项- 更新该 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
问题
我应该如何使用猫鼬来做到这一点?
解决方案
如果你有一个 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
在猫鼬下使用
我的建议:
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
推荐阅读
- react-router - Jhipster - 反应路由问题
- javascript - 单击水平折叠折叠组件手风琴样式
- python - 如何创建嵌套字典键并从命名空间键值对列表中为其分配值?
- php - 从 HTML 表单中插入一行或多行
- batch-file - 检查文件是否存在,然后将数字附加到名称
- jquery - 当用户单击单选按钮时,隐藏所有其他选项并使标签放大和动画?
- xml - 来自示例 XML 的 XSD
- quanteda - dfm(Quanteda)中“remove_twitter”的新方法是什么?
- javascript - 未捕获的 TypeError:无法将 undefined 或 null 转换为对象 React JS
- ios - 可扩展的 UICollectionView 单元格