我的模型看起来像这样:
mongoose.Schema({
username: String,
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});
我有一个端点,我想传递一个ObjectID:
app.delete('/post', function(req, res) {
User.findOne({ _id: req.user._id}, function(err, result) {
result.pull({ _id: req.body.post_id });
});
});
感觉它应该有效,但我收到了这个错误:
CastError: Cast to ObjectId failed for value "[object Object]"
我做错了什么?
答案 0 :(得分:1)
如果要从数组中删除一个元素,请使用此
User
.update(
{_id: req.user._id},
{ $pull: {posts: req.body.post_id } }
)
.then( err => {
...
});
答案 1 :(得分: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 http://stackoverflow.com/questions/3396088/how-do-i-remove-an-object-from-an-array-with-javascript
});
then you can do slice on array of object
答案 2 :(得分:-1)
为了在集合中使用id进行研究,您需要创建一个新的ObjectId,然后将id传递给它。
adb shell am start -n com.mediatek.camera/com.android.camera.CameraActivity