2016-11-21 38 views
0

我想在使用節點js的mongoDB中的子文檔中添加一個值。 的模式是:使用Nodejs查詢MongoDB中的SuDocument

var commentSchema = new Schema({ 
    author:String, 
    data:String, 
    postedAt:Date 
}); 

var likeSchema = new Schema({ 
    likedBy:{ 
     type:Array, 
     default:[""] 
    }, 
    numOfLikes:{ 
     type:Number, 
     default:0 
    } 
}); 

var picSchema = new Schema({ 
    url:String, 
    likes:[likeSchema], 
    comments:[commentSchema] 
}); 

var statusSchema = new Schema({ 
    data:String, 
    likes:[likeSchema], 
    comments:[commentSchema] 
}); 

var profileSchema = new Schema({ 
    username:String, 
    password:String, 
    DOB :Date, 
    sex: String, 
    Address:String, 
    pic:[picSchema], 
    Status:[statusSchema] 
}); 

我想一個用戶添加到其他用戶的PIC評論。 ,我使用的是現在的方法是:

profile.update({"username":recepient,"pic._id":id},{$set:{"pic.comments":{"author":user,"data":comment,"postedAt":new Date()}}}},function(err,data){ 
        if (err){ 
         throw err; 
        }else{ 
         console.log(data); 
         res.status(200).json({status:"Added successfully"}); 
        } 

在這裏,我得到的錯誤是:不能用pic.comments的一部分PIC遍歷。

當我使用update語句:

profile.update({"username":recepient,"pic._id":id},{$set:{"comments":{"author":user,"data":comment,"postedAt":new Date()}}},function(err,data){ 
        if (err){ 
         throw err; 
        }else{ 
         console.log(data); 
         res.status(200).json({status:"Added successfully"}); 
        } 

我沒有得到任何錯誤,但沒有得到增值。

更新語句或模式有一些錯誤嗎?

回答

0

檔案[圖]產品圖[評論],如果你想更新產品圖通過"pic._id":id那麼你應該查詢產品圖模型,而不是簡介。子文檔有點像SQL表

pic.update({ // update Pic model, not Profile 
    "pic._id": id // removed "username":recepient as you already have picId 
    }, { 
    $set: { 
     "comments": { 
     "author": user, 
     "data":comment, 
     "postedAt":new Date() 
     } 
    } 
    }, function(err,data){ 
     if (err){ 
     throw err; 
     console.log(data); 
     res.status(200).json({status:"Added successfully"}); 
    } 
+0

這裏的數據庫是在一個單獨的文件中定義的。從那裏我出口profileSchema模塊。這種導出現在也在其他地方使用,例如護照認證。所以當我在數據庫文件中寫入兩個導出語句時,我在護照驗證功能中遇到錯誤。因爲,那裏我們'需要'文件,從導出的'模塊'被調用的地方。 對此有何想法? –