I have the following Schema:
我有以下架构:
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
movies : [{
moviename : String,
rating : Number
}],
}
});
And I use the following way to add entries to the array:
我使用以下方法向数组添加条目:
user.local.movies.push({ moviename : "Top Gun", rating : 80});
user.save(function (err) {
if (err)
console.log("Error in saving");
res.end(0);
});
But I need to remove entries too. I need to be able to remove entries by the "moviename" name. I tried using pull:
但我也需要删除条目。我需要能够通过“moviename”名称删除条目。我试过用拉:
user.local.movies.pull({ moviename : "Top Gun"});
but it did not work.
但它不起作用。
Could someone please let me know how I can remove entries from the array?
有人可以告诉我如何从阵列中删除条目吗?
Thank you.
谢谢。
2 个解决方案
#1
2
I think it's easier to use an explicit update
call instead of Mongoose's array manipulation methods which don't always work as you'd expect:
我认为使用显式更新调用更容易,而不是Mongoose的数组操作方法,这些方法并不总是像您期望的那样工作:
User.update({_id: user._id},
{$pull: {'local.movies': {moviename: 'Top Gun'}}}, callback);
#2
1
One way of doing this is to use the splice function to remove the element from the array, assuming you can find the index. So for instance:
一种方法是使用splice函数从数组中删除元素,假设您可以找到索引。例如:
User.findOne(function(err, user) {
var movies, index;
movies = user.movies;
for (index = 0; index < movies.length; index++) {
if (movies[index].moviename === "Top Gun") {
break;
}
}
if (index !== movies.length) {
movies.splice(index, 1);
}
user.save(function(err, user) {
res.send(user);
});
});
(Know that the above code does this for only one user, and hard codes the movie name to remove, but you get the idea.)
(知道上面的代码只针对一个用户执行此操作,并且硬编码要删除的影片名称,但您明白了。)
#1
2
I think it's easier to use an explicit update
call instead of Mongoose's array manipulation methods which don't always work as you'd expect:
我认为使用显式更新调用更容易,而不是Mongoose的数组操作方法,这些方法并不总是像您期望的那样工作:
User.update({_id: user._id},
{$pull: {'local.movies': {moviename: 'Top Gun'}}}, callback);
#2
1
One way of doing this is to use the splice function to remove the element from the array, assuming you can find the index. So for instance:
一种方法是使用splice函数从数组中删除元素,假设您可以找到索引。例如:
User.findOne(function(err, user) {
var movies, index;
movies = user.movies;
for (index = 0; index < movies.length; index++) {
if (movies[index].moviename === "Top Gun") {
break;
}
}
if (index !== movies.length) {
movies.splice(index, 1);
}
user.save(function(err, user) {
res.send(user);
});
});
(Know that the above code does this for only one user, and hard codes the movie name to remove, but you get the idea.)
(知道上面的代码只针对一个用户执行此操作,并且硬编码要删除的影片名称,但您明白了。)