Mongoose:根据ID从数组中删除对象(类型错误)

9

我有一个模型,看起来像这样:

mongoose.Schema({
  username: String,
  posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});

我有一个终端点(endpoint),我想通过一个ObjectID传递参数:

app.delete('/post', function(req, res) {
  User.findOne({ _id: req.user._id}, function(err, result) {
    result.pull({ _id: req.body.post_id });
  });
});

感觉应该可以工作,但是我收到了这个错误:

CastError: 将值“[object Object]”转换为ObjectId失败

我做错了什么?

3个回答

10
如果您想从数组中删除一个元素,请使用此方法。
User
.update( 
  {_id: req.user._id}, 
  { $pull: {posts: req.body.post_id } } 
)
.then( err => {
  ...
});

这里是文档


0
This is because when you are running user findOne query it returns an object to you.(the findOne function returns only one object)

User.findOne({ _id: req.user._id}, function(err, result) {

 /// result is an object
    result.pull({ _id: req.body.post_id });
  });

and what is result.pull you are trying to pull an element from object this is the wrong way to do

do like this 
delete result._id;


and if you want more elements from user query in from of array you can use 
User.find({ _id: req.user._id}, function(err, result) {

// result.slice for slice you can see this https://dev59.com/NXA75IYBdhLWcg3wP2kg
  });

then you can do slice on array of object

-1
为了在集合中使用 ID 进行研究,您需要创建一个新的 ObjectId,然后将该 ID 传递给它。
app.delete('/post', function(req, res) {
    User.findOne({ _id: _id: ObjectId (req.user._id)}, function(err, result) {
        result.pull({ _id: ObjectId (req.body.post_id) });
    });
 });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接