简体   繁体   English

如何从 Mongodb 中删除数组元素

[英]How to remove an array element from Mongodb

I'm new to MEAN stack.我是 MEAN 堆栈的新手。 I'm trying to implement this and this .我正在尝试实现thisthis I'm using $pull .我正在使用$pull But they ain't working maybe because my structure in mongodb is different from theirs.但它们不起作用可能是因为我在 mongodb 中的结构与他们的不同。 So let me first show you that:所以让我首先告诉你:

在此处输入图片说明

downvoters is an string array that contains userids who downvoted that particular article. downvoters是一个字符串数组,其中包含对该特定文章投反对票的用户 ID。 Lets say the person on downvoters[2] ie 53et853rf later upvoted this article.Then his userid should be removed from downvoters list.让我们说downvoters[2]上的人,即53et853rf后来upvoted这篇文章。那么他的用户ID应该从downvoters列表中删除。 Here is my code:这是我的代码:

api.js api.js

router.put('/update-upvotes', (req, res) => {
  let articleData = req.body;
  ...
  Article.update(
    {articleid: '5p4aqbryi'},
    { $pull: { downvoters: '53et853rf' } }
  );
  Article.findOneAndUpdate(
    {articleid: '5p4aqbryi'},
    {upvotes: articleData.upvotes, upvoters: articleData.upvoters}, useFindAndModify=false,
    (error, user) => {
      if(error) {
        ...
      }
      else {
        ...
      }
    })
   })

But that id is not deleted.但是那个id没有被删除。 There's no error or warning on console.控制台上没有错误或警告。 Please correct me.请纠正我。

And here is the schema这是架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const articleSchema = new Schema({
  articleid: String,
  title: String,
  content: String,
  date: String,
  contributor: String,
  upvotes: Number,
  upvoters: [],
  downvotes: Number,
  downvoters: []
})
module.exports = mongoose.model('article', articleSchema, 'articles');

PS: Let articleId and downvoter id be hardcoded now. PS:现在让articleIddownvoter id被硬编码。 I'll make them dynamic later.稍后我会让它们变得动态。

Both upvoters and downvoters are String arrays so your Mongoose schema should look like below: upvotersdownvoters都是String数组,因此您的 Mongoose 架构应如下所示:

const articleSchema = new Schema({
    articleid: String,
    title: String,
    content: String,
    date: String,
    contributor: String,
    upvotes: Number,
    upvoters: [String],
    downvotes: Number,
    downvoters: [String]
});

You should also keep in mind that update() is an asynchronous operation which needs to be awaited or handled as Promise so:您还应该记住update()是一个异步操作,需要作为 Promise awaited或处理,因此:

let opResult = await Article.update(
    {articleid: '5p4aqbryi'},
    { $pull: { downvoters: '53et853rf' } }
);

or或者

Article.update(
        { articleid: '5p4aqbryi' },
        { $pull: { downvoters: '53et853rf' } }
    ).then(opResult => console.log(opResult));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM