mongoose中确定元素是否已存在于数组中的最快方法是什么。在这种情况下,我想删除该数组中的元素。如果数组不包含我想要添加的特定元素。
当然可以使用addToSet和remove(_id)来完成添加和删除。查询也没问题。我真的更关心用最短的方式做到这一点,而不费力。
例如,我建议采用架构:
var StackSchema = new Schema({
references: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
假设引用数组包含元素:
['5146014632B69A212E000001',
'5146014632B69A212E000002',
'5146014632B69A212E000003']
案例1:我的方法收到5146014632B69A212E000002 (因此应删除此条目。)
案例2:我的方法收到5146014632B69A212E000004(因此应该添加此条目。)
答案 0 :(得分:2)
任何路过的人的解决方案。 :)
if(doc.references.indexOf(SOMESTRING) !== -1) {
console.log('it\'s there') ; doc.likes.pull(SOMESTRING);
}else{
doc.references.push(SOMESTRING);
}
答案 1 :(得分:0)
这是逻辑,代码如下。
我通常使用underscore.js来完成这些任务,但你可以用JavaScript来完成。
array.push()
_id。然后document.save()
这就是我通常遵循的方法。
在下划线中,它会是这样的:
function matching(a,b) { // a should be your _id, and b the array/document
var i;
for ( i = 0, i < b.length , i++) {
if ( a.toString() === b[i].toString() )
return i;
else return -1;
}
};
然后你就可以使用这个功能了:
var index = matching( '5146014632B69A212E000002', doc );
if ( index > -1 )
doc.splice( index , 1);
else
doc.push( '5146014632B69A212E000002' );
答案 2 :(得分:0)
@侯赛因答案,但使用Lodash:
const _ = require("lodash")
const User = require("./model")
const movies = ["Inception", "Matrix"]
(async () => {
// Catch errors here
const user = User.findById("")
const userMoviesToggle = _.xor(
user.movies, // ["Inception"]
movies
); // ["Matrix"]
user.movies = userMoviesToggle
// Catch errors here
user.save()
})()