Mongoose 从数组中拉取 ObjectId [英] Mongoose pull ObjectId from array

查看:40
本文介绍了Mongoose 从数组中拉取 ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个非常简单的操作,在 Mongo 数据库上使用 Mongoose 从数组中提取一个项目,如下所示:

i'm trying to do a pretty simple operation, pull an item from an array with Mongoose on a Mongo database like so:

User.update({ _id: fromUserId }, { $pull: { linkedUsers: [idToDelete] } });

fromUserId &idToDelete 都是对象 ID.

fromUserId & idToDelete are both Objects Ids.

用户的架构是这样的:

var UserSchema = new Schema({
  groups: [],
  linkedUsers: [],
  name: { type: String, required: true, index: { unique: true } }
});

linkedUsers 是一个只接收其他用户 ID 的数组.

linkedUsers is an array that only receives Ids of other users.

我也试过这个:

User.findOne({ _id: fromUserId }, function(err, user) {
  user.linkedUsers.pull(idToDelete);
  user.save();
});

但没有运气.

当我在不同位置控制数组的长度时,第二个选项似乎几乎可以工作,但在调用 save 并检查后,长度仍为 36:

The second option seem to almost work when i console the lenghts of the array at different positions but after calling save and checking, the length is still at 36:

 User.findOne({ _id: fromUserId }, function(err, user) {
    console.log(user.linkedUsers.length); // returns 36
    user.linkedUsers.pull(idToDelete);
    console.log(user.linkedUsers.length); // returns 35
    user.save();
  });

所以看起来我很接近但仍然没有运气.两个 ID 都是通过应用程序的前端发送的.我正在运行这些版本:

So it looks like i'm close but still, no luck. Both Ids are sent via the frontend side of the app. I'm running those versions:

"mongodb": "^2.2.29",
"mongoose": "^5.0.7",

提前致谢.

推荐答案

您需要在架构定义中明确定义类型,即

You need to explicitly define the types in your schema definition i.e.

groups: [{ type: Schema.Types.ObjectId, ref: 'Group' }], 
linkedUsers: [{ type: Schema.Types.ObjectId, ref: 'User' }]

然后使用

User.findOneAndUpdate( 
    { _id: fromUserId }, 
    { $pullAll: { linkedUsers: [idToDelete] } }, 
    { new: true }, 
    function(err, data) {} 
);

User.findByIdAndUpdate(fromUserId, 
    { $pullAll: { linkedUsers: [idToDelete] } }, 
    { new: true }, 
    function(err, data) {} 
);

这篇关于Mongoose 从数组中拉取 ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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