search

Home  >  Q&A  >  body text

mongodb - How to add or remove documents to array properties in mongoose?

Like the example below, if I want to add or delete documents to the lists array, what should I do? Thanks!

{
    "_id" : ObjectId("590a77315a7ae88824b296cf"),
    "user" : "yejia@qq.com",
    "password" : "5475442343",
    "lists" : [
        {
            "create_at" : "1234",
            "update_at" : "1234",
            "title" : "yejia",
            "list_id" : 123
        }
    ]
}
伊谢尔伦伊谢尔伦2774 days ago707

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-17 10:05:17

    pull and push are the same as MongoDB Node.JS Driver.

    Refer to the following usage:

    Model.update({ }, {’$pull’:{ } } );

    Model.update({ }, {’$push’:{ } } );

    For reference

    Love MongoDB! Have Fun!


    The syntax reference for Mongoose’s pull and push is as follows:

    var schema = new mongoose.Schema({ user: 'string', password: 'string', lists: [ {create_at: 'string', update_at: 'string', title: 'string', list_id: 'number'}]});
    
    var User = mongoose.model('User', schema,'test');
    
    //删除
    User.update({"user" : "yejia@qq.com"}, 
    {'$pull':{ lists : { list_id : 123 }}}, function(err, data){
        if(err) {
            console.log(err);}
        console.log(data);
        });
    
    //添加
    User.update({"user" : "yejia@qq.com"}, 
    {'$push':{ lists : { create_at: '111', update_at: '222', title: 'test', list_id: 8888}}}, function(err, data){
        if(err) {
            console.log(err);}
        console.log(data);
        });
    
    //打印结果
    User.find({},function(err,result){
        console.log(result);
    });
    

    reply
    0
  • Cancelreply