【发布时间】:2018-06-01 08:42:14
【问题描述】:
使用 Mongoose,我无法将位置数据插入数据库:
Can't extract geo keys from object, malformed geometry?
似乎 POST 请求正常(LOG A):它有一个位置('loc')字段,但我从这个 POST 请求创建的对象缺少 'loc' 字段数据:
这是我的架构:
models/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'});
routes/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)});
});
...
这是输出:
日志 A:req.body.article
{ title: 'article title',
description: 'about section',
body: 'Article body',
tagList: [],
loc: '{"type":"Point","coordinates":[38.9173025,-77.220978]}'
}
LOG 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
【问题讨论】:
-
不能转换它,因为它是字符串(注意 Log A 输出中 loc 变量的值周围的单引号),而 mongoose 需要对象?
标签: node.js mongodb mongoose geolocation mongoose-schema