2016-11-21 69 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模块。这种导出现在也在其他地方使用,例如护照认证。所以当我在数据库文件中写入两个导出语句时,我在护照验证功能中遇到错误。因为,那里我们'需要'文件,从导出的'模块'被调用的地方。 对此有何想法? –