How to add data to array in Mongoose Schema

让人想犯罪 __ 提交于 2019-12-29 09:59:23

问题


Assuming the following schema, I am trying to save some GeoJSON data with Mongoose

var simpleSchema = new Schema({
    properties:{
        name:String,
        surname:String
    },
    location : {
        type : String,
        coordinates : [ Number , Number ]
    }
});

This is how I try to save the document

var a = new simple({properties:{name:"a", surname:"b"}, location:{type:"Point", coordinates:[1, 0]}}).save(function(err){...});

However, what I am getting in the database is

ObjectId("542da9ab0882b41855ac3be0"), "properties" : { "name" : "a", "surname" : "b" }, "__v" : 0 }

It looks like the whole location tag and data are missing. Is this a wrong way to define a schema or a wrong way of saving the document?


回答1:


When using a field named type in an embedded object, you need to use an object to define its type or Mongoose thinks you're defining the type of object itself.

So change your schema definition to:

var simpleSchema = new Schema({
    properties:{
        name:String,
        surname:String
    },
    location : {
        type : { type: String },
        coordinates : [ Number , Number ]
    }
});


来源:https://stackoverflow.com/questions/26168415/how-to-add-data-to-array-in-mongoose-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!