Mongoose - 嵌入的文档保存为字符串

时间:2013-12-10 07:13:45

标签: node.js mongodb express mongoose pug

在我的节点应用中,我有designation模型,其中包含以下Schema

var DesignationSchema = new Schema({
    _id : ObjectId,
    designation : String
});

这嵌入在users架构中。

var UserSchema = new Schema({
    fname:String,
    lname :String,
    email :String,
    password :String,
    designations : [DesignationSchema]
});

用户可以从designations列表中选择一个/多个select。以下是我创建选择列表的jade实现;

select(name="designations")
- for(var i = 0; i < designations.length; i++) {
    option(value="#{designations[i]}", name="designations[#{i}]") #{designation.designation}
- }

但这些值存储为string数组而不是DesignationSchema数组:

{
    designations : ["{designation:'Some Value' , _id : __DESIGNATION__ID}", "{designation:'Some Value' , _id : __DESIGNATION__ID}"]
}

更新 我在expressjs

中以下列方式推动指定
var newUser = new User(user.info);
if(user.designations && user.designations.length){
  for(var i =0; i < user.designations.length; i ++) {
    newUser.designations.push(user.designations[i]);
    //I have tried JSON.parse(user.designations[i]) but it raises error that says : 'Unexpected token d'
   //user.designations[i] object is something like : {designation:'Some Content', _id : __DESIGNATION__ID} 
   //IMPORTANT : the __DESIGNATION__ID is not inside single (') or double (") quotes. And I think this is the reason why JSON.parse is raising the error.
  }
}

1 个答案:

答案 0 :(得分:0)

您可以从DesignationSchema中省略_id,因为Mongoose会为您自己添加。确保你JSON.stringify您POST / PUT / etc的数据,以便留下你可以解析的东西。

您可能还需要在发回数据时将内容类型指定为application / json。这应该允许您避免端点中的JSON.parse。