问题描述
我正在尝试做一个非常简单的操作,使用Mongoose在Mongo数据库上从数组中提取项,如下所示:
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) {}
);
这篇关于猫鼬从数组中拉ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!