Node.js mongoose-如果不在数组中,则添加,如果已在数组中,则删除
在mongoose中,确定元素是否已在数组中的最快方法是什么。在这种情况下,我想从该数组中删除元素。在数组不包含特定元素的情况下,我要添加它 当然,可以使用addToSet和remove(_id)进行添加和删除。查询也没有问题。我真的更关心的是用更少的努力,用最短的方法来做这件事 例如,我建议采用以下模式:Node.js mongoose-如果不在数组中,则添加,如果已在数组中,则删除,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,在mongoose中,确定元素是否已在数组中的最快方法是什么。在这种情况下,我想从该数组中删除元素。在数组不包含特定元素的情况下,我要添加它 当然,可以使用addToSet和remove(_id)进行添加和删除。查询也没有问题。我真的更关心的是用更少的努力,用最短的方法来做这件事 例如,我建议采用以下模式: var StackSchema = new Schema({ references: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
var StackSchema = new Schema({
references: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
假设references数组包含以下元素:
['5146014632B69A212E000001',
'5146014632B69A212E000002',
'5146014632B69A212E000003']
案例1:我的方法接收5146014632B69A212E000002
(因此应删除此条目。)
案例2:我的方法接收5146014632B69A212E000004(因此应添加此条目)。以下是逻辑,代码如下 我通常使用下划线.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;
}
};
任何路过的人的解决方案。:)
@侯赛因回答,但使用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()
})()
if(doc.references.indexOf(SOMESTRING) !== -1) {
console.log('it\'s there') ; doc.likes.pull(SOMESTRING);
}else{
doc.references.push(SOMESTRING);
}
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()
})()