用mongoose保存数组?

时间:2018-02-18 11:48:08

标签: node.js mongodb mongoose

我一直在尝试在Mongoose中保存 arrray 数据。这是我的猫鼬模式

    var uploadSchema = mongoose.Schema({
    Fbid: String,
    email: String,
    events: [String],
    uplodedImg: [String],

})

这就是我想要保存的方式,但是在robomongo中没有任何东西 我在这里做错了什么

 var uploadImf = new usersuploadImformation({
    Fbid : fb_id,
    email: email,
    events: place ,
    uploadedImg : randome  

});
usersuploadImformation.findOne({
    Fbid : uploadImf.Fbid
},function(err,check){
    if(!check){
        uploadImf.save(function(err, uploadImf){
            if(err){
               console.log("Error found");
            }
            else{
                console.log("Saved");
            }
        })
    }})

我想更新这些字段

    {
    "_id" : ObjectId("5a895f520ea9692308ffcf13"),
    "events" : [],
    "uplodedImg" : [],
    "Fbid" : "1661115317267347",
    "email" : "1407258@kiit.ac.in",
    "__v" : 0
}

尝试使用其他代码进行更新和保存:

    usersuploadImformation.findOne({Fbid : fb_id},function(err, check){
    if(!check){
        new usersuploadImformation({
            Fbid : fb_id,
            email: email,
            events: place ,
            uploadedImg : randome  
        }).save(function(err, uploadImf){
            if(err){
               console.log("Error found");
            }
            else{
                console.log("Saved");
            }
        });
    }
    else{
        check.events.push({place})
        check.uploadedImg.push({randome})
        check.save();
    }
})

它应至少保存一次,我还没有写过更新的情况。

1 个答案:

答案 0 :(得分:2)

尝试更改类似的代码,

var query = { 'Fbid': fb_id },
    update = {
        $set: { email: email },
        $push: {
            events: place,
            uploadedImg: randome
        }
    },
    options = { upsert: true };

usersuploadImformation.findOneAndUpdate(query, update, options, function (err, data) {
    if (err) {
        // **   
    }
    // ** your extra code       
});

这里的upsert是什么,如果你的数据库中没有文档,那么它会自动为你保存文档。

$set将更新给定字段,$push将推送到事件数组,并将randome推送到uploadImg数组。