Expressjs collection.update $push result with TypeError: Cannot call method 'update' of undefined

Expressjs collection.update $push result with TypeError: Cannot call method 'update' of undefined

我尝试创建有效的 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;

所以如果一切正常,但为什么在执行 post 路线后我得到

TypeError: Cannot call method 'update' of undefined

我也检查了 mongo shell 中的命令并且有效

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

问题是 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');
});