使用TypeError的Expressjs collection.update $ push结果:无法调用undefined的方法'update'

时间:2015-02-27 16:22:25

标签: mongodb express mongoose geojson

我尝试创建有效的geojson FeatureCollection,并且在更新集合中的文档时出现了一些问题。

我的模特

var mongoose = require('mongoose');

Schema = mongoose.Schema;

var DataSchema = new Schema({
  type: {type:String, default:"Feature"},
  properties:{
  title: { type: String, required: true },
  description: { type: String, required: true},
  date: {type:Date, default:Date.now}},
  geometry:{
  type:{type:String, default:"Point"},
  coordinates: {type: [Number]}}
  });

  var MetadataSchema = new mongoose.Schema({
    type  : {type: String, default: "FeatureCollection"},
    features: [DataSchema]
  });

 var rescueModel = mongoose.model('rescueModel', MetadataSchema);

路由器

router.post('/mountain_rescue', function(req, res){
  db.collection('rescuemodels', function(err, collection){
    collection.update({
      "type": "FeatureCollection"
    },
    {
      $push: {
        "features": {
          properties: {
            title: req.body.title,
            description: req.body.description
          },
          geometry: {
            coordinates: req.body.coordinates.split(',')
          }
        }
      }
    });
  res.redirect('/mountain_rescue');
  });
});
module.exports=rescueModel;

所以如果一切都好,但为什么在执行后路线后我得到了

  

TypeError:无法调用undefined

的方法'update'

我还检查了mongo shell中的命令,它可以正常工作

db.rescuemodels.update(
    {
       "type":"FeatureCollection"
    },  
    {
       $push:{
           "features": {
               "properties":{"title":"WOW"} 
            } 
       } 
    }
)

1 个答案:

答案 0 :(得分:1)

问题是在运行更新之前未定义collection。此外,您可能希望在回调中对update函数进行重定向,但这取决于您要查找的行为。您的代码看起来像这样:

var collection = db.collection('rescuemodels');
collection.update({
  "type": "FeatureCollection"
},
{
  "$push": {
    "features": {
      "properties": {
        "title": req.body.title,
        "description": req.body.description
      },
      "geometry": {
        "coordinates": req.body.coordinates.split(',')
      }
    }
  }
}, function(err, result) {
    if (err) throw err;

    res.redirect('/mountain_rescue');
});