在我的节点应用中,我有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.
}
}
答案 0 :(得分:0)
您可以从DesignationSchema中省略_id,因为Mongoose会为您自己添加。确保你JSON.stringify您POST / PUT / etc的数据,以便留下你可以解析的东西。
您可能还需要在发回数据时将内容类型指定为application / json。这应该允许您避免端点中的JSON.parse。