最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

无法使用位置字段创建Mongoose对象

运维笔记admin17浏览0评论

无法使用位置字段创建Mongoose对象

无法使用位置字段创建Mongoose对象

使用Mongoose,我无法将位置数据插入数据库:

Can't extract geo keys from object, malformed geometry?

似乎POST请求没问题(日志A):它有一个位置('loc')字段,但我从这个POST请求创建的对象缺少'loc'字段数据:

这是我的架构:

车型/ Article.js

var ArticleSchema = new mongoose.Schema({
    slug: {type: String, lowercase: true, unique: true},
    title: String,
    description: String,
    body: String,
    loc :  { type: {type:String}, coordinates: [Number]},
    favoritesCount: {type: Number, default: 0},
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
    tagList: [{ type: String }],
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, {timestamps: true});

ArticleSchema.index({loc: '2dsphere'});

路线/ Article.js

router.post('/', auth.required, function(req, res, next) {
  User.findById(req.payload.id).then(function(user){
      if (!user) { return res.sendStatus(401); }

      var article = new Article(req.body.article);

      // LOG A
      console.log(req.body.article);

      // LOG B
      console.log(article);

      article.author = user;

      return article.save().then(function(){
         return res.json({article: article.toJSONFor(user)});
      });
      ...

以下是输出:

日志 - 答:req.body.article

{ title: 'article title',
  description: 'about section',
  body: 'Article body',
  tagList: [],
  loc: '{"type":"Point","coordinates":[38.9173025,-77.220978]}' 
}

日志B:使用var article = new Article(req.body.article)创建的文章;

{ loc: { coordinates: [] },
  favoritesCount: 0,
  comments: [],
  tagList: [],
  _id: 5a384f502c9912312c6dd89d,
  body: 'Article body',
  description: 'about section',
  title: 'article title' 
}

我的问题是,当创建对象“文章”时,loc字段开始“{coordinates:[]}”而不是{“type”:“Point”,“coordinates”:[38.9173025,-77.220978]}。

为什么位置数据不在Object中?

我一直在寻找这个问题:Location in mongoose, mongoDB

回答如下:

感谢@Veeram:问题是我的POST请求:该位置是以字符串而不是对象的形式发送的:

在我的Angular前端:

article.model.ts之前

export class Article {
  ....
  loc: string
  ....
}

article.model.ts后

class Location {
  constructor(
    public type: string,
    public coordinates: Array<number> = []
  ){}
}

export class Article {
  ....
  loc: Location
  ....
}
发布评论

评论列表(0)

  1. 暂无评论