NodeJS/Mongoose/MongoDB-拉(从阵列​​)不起作用 [英] NodeJS/Mongoose/MongoDB - Pull (from array) not working

查看:55
本文介绍了NodeJS/Mongoose/MongoDB-拉(从阵列​​)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组(子文档)中提取/删除值.

I am trying to pull/remove values from an array (subdocument).

示例文档:

{
   _id: 5150a1199fac0e6910000002,
   name: 'some name,
   items: [{
      id: 23,
      name: 'item name 23'
   },{
      id: 24,
      name: 'item name 24'
   }]
}

当我已经从mongo中提取文档时,我的文档已经在内存中.我正在尝试:

I have the doc in memory as I pulled it from mongo already. I am trying:

var left = object.items.pull({id: 24});
console.log(left)

输出:

[{
   id: 23,
   name: 'item name 23',
   _id: 5150a1199fac0e6910000045
},{
  id: 24,
  name: 'item name 24',
  _id: 5150a1199fac0e6910000002 
}]

看来我已经有问题了.从pull调用返回的数组应该是pull之后剩下的数组.不知道为什么它没有从item数组中提取.这是否仅支持通过ObjectId ant提取而不是用户定义的字段?

So looks like I already have a problem. The array returned from the pull call should be whats left in the array after the pull . Not sure why it did not pull from the item array. Does this only support pulling by ObjectId ant not user defined fields?

我叫保存:

object.save();

猫鼬将此记录为查询:

Mongoose: mycollection.update({ _id: ObjectId("5150901ac345824a07000002"), __v: 3 }) 
  { '$inc': { __v: 1 }, '$pull': 
    { attachments: { _id: { '$in': [ ObjectId("5150c64d63773efb1f000002") ] } } } } {}

这显示了为什么不删除我的文档的原因.应当删除的数组项的_id为:

This shows why my document is not being removed. The _id of the array item that should be removed is:

_id: 5150a1199fac0e6910000002

猫鼬发送到数据库中要删除的项目是:

The item that mongoose is sending to the database to remove is:

ObjectId("5150c64d63773efb1f000002")

有什么想法我做错了吗?我正在尝试通过_id以外的其他内容删除,不确定是否可行,但是从文档中可以看到.

Any ideas what I am doing wrong? I am trying to delete by something other than _id, not sure if that is possible but from the docs looks to be.

推荐答案

我发现$ pull命令对我也不起作用,除非我在参数列表中包含回调.

I discovered that the $pull command doesn't work for me either unless I include the callback in the arguments list.

在我的情况下,这种格式不起作用:

In my situation, this format did not work:

UserAlerts.findOneAndUpdate({userId: userId}, {$pull: {alerts: {_id: alertId}}});

但是这种格式可以做到:

But this format did:

UserAlerts.findOneAndUpdate({userId: userId}, {$pull: {alerts: {_id: alertId}}}, function(err, data){
  console.log(err, data);
});

根据文档,似乎两者都应该起作用,但是不起作用.原因是因为第一种方法要求您在返回的对象上调用.exec(),而回调版本会自动调用exec().也给我造成了一些困惑.

According to the documentation, it seems like both should work, but don't. The reason is because the first way requires you to call .exec() on the returned object, whereas the callback version calls exec() automatically. Caused some confusion for me also.

因此,您需要执行以下操作:

So you need to do something like this:

UserAlerts.findOneAndUpdate({userId: userId}, {$pull: {alerts: {_id: alertId}}}).exec();

这篇关于NodeJS/Mongoose/MongoDB-拉(从阵列​​)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆