I have a schema
var mySchema = new Schema({
array: []
});
var PSchema = mongoose.model('objects', mySchema);
I've added 1 element called 'hello' to the array property in a schema object
var newObject = new PSchema;
newObject.array.push('hello');
newObject.save(function (err) {});
I want to update the schema object to add 'hello2' to the array property if and only if hello2 doesn't already exist in the array.
Is this possible with mongoose? If so, how do i do this?
You can make use of the find()
function and then perform an update
.
PSchema.find({},function(err,docs){
docs.forEach(function(doc){
if(doc.array.indexOf("hello2") == -1)
{
doc.array.push("hello2");
doc.save(function (err) {
if(err) {
//error
}
});
}
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.