使用 mongoose 5.12 从数组中删除对象($pull 不起作用)

时间:2021-06-29 21:54:04

标签: arrays object mongoose pull remove

我在使用 mongoose 5.12 时遇到了问题。

{
  "_id": {
    "$oid": "60db70c9956a6c4d0645d447"
  },
  "articles": [
    {
      "_id": {
        "$oid": "60db8764da322a23e787ca3d"
      },
      "type": "Déssert",
      "name": "dfd",
      "description": "",
      "price": 0,
      "tag": "",
      "picture": "noarticle.jpg"
    },
  ],
  "editor": 27,
}

我的餐厅文档包含文章(对象数组)

我想从中删除一篇文章。

但是当我使用它时:

const deletedArticle = await this.restaurantModel.findOneAndUpdate(
  { editor: userId },
  { $pull: { articles: articleId } },
  { multi: true, new: true, useFindAndModify: true },
);

// userId -> 27 and articleId --> "60db8764da322a23e787ca3d"

但没有任何变化。

这是 _id 类型的问题吗?或者其他什么?

($push 选项有效)

1 个答案:

答案 0 :(得分:0)

你做错了:

from datetime import datetime
from flask import render_template, session, redirect, url_for, flash
from .. import db
from ..models import User, Role, Location, Demo, Question, Answer, DemoType, DemoReport, DemoRptQ
from ..email import send_email
from . import main
from .forms import DashboardForm, EditProfileForm, EditProfileAdminForm, DemosForm, DemoForm
from .forms import QuestionsForm, QuestionForm, DemoTypesForm, DemoTypeForm, DemoReportsForm, DemoReportForm
from .forms import AnswerForm, AnswersForm, LocationsForm, LocationForm
from .forms import UsersForm
from flask_login import login_required, current_user
from ..decorators import admin_required
from wtforms.validators import DataRequired, Optional, Length


@main.route('/', methods=['GET', 'POST'])
def index():
    form = DashboardForm()
    if form.validate_on_submit():
        btn = form.submit.raw_data[0]
        if btn == 'Demos':
            return redirect(url_for('.demos_list'))
        elif btn == 'New Demo':
            return redirect(url_for('.edit_demo', id=0))
        elif btn == 'Login':
            return redirect(url_for('auth.login'))
        elif btn == 'Register':
            return redirect(url_for('auth.register'))

    return render_template('index.html', form=form, isauth=current_user.is_authenticated)

@main.route('/users')
def users_list():
    form = UsersForm()
    if form.validate_on_submit():
         return redirect(url_for('.index'))

应该是:

{ $pull: { articles: articleId } }

或者:

{ $pull: { articles: { _id : articleId } } }