简体   繁体   English

插入Mongodb集合(新手)

[英]Inserting Into A Mongodb Collection (Newbie)

I'm new to nodejs and mongodb. 我是nodejs和mongodb的新手。 I'm trying to insert newClass into the class collection. 我正在尝试将newClass插入到类集合中。 Everything seems to be working except this function. 除此功能外,其他所有功能似乎都可以正常工作。 It gives a 500 error and doesn't save the class. 它给出一个500错误,并且不保存该类。

I checked the mongodb docs and it seemed correct. 我检查了mongodb文档,它似乎是正确的。 Can someone please point me in the right direction? 有人可以指出正确的方向吗?

routes 路线

Class.createNewClass(newClass, function(err){
    if (err){
        console.log(err);
        res.send(err);
    } else {
        console.log('Class saved.")
    }
})

model 模型

module.exports.createNewClass = function(newClass, callback){
    Class.insert({newClass}, callback);
}

There's a syntax error in your createNewClass function, assuming the newClass variable is an object that contains all the key:value pairs you're saving to the new document, you should remove the curly braces: 假设newClass变量是一个对象,其中包含要保存到新文档中的所有key:value对,则createNewClass函数中存在语法错误,您应该删除花括号:

module.exports.createNewClass = function(newClass, callback){
    Class.insert(newClass, callback);
}

That said, the code you posted for your routes doesn't look much like a route to me, so there could be other errors your transcription is not revealing. 就是说,您为路线发布的代码看起来不太像是通往我的路线,因此您的转录可能没有发现其他错误。

I'm not really clear on the overall structure of your app, but here is a very simple Express app that can insert new classes to the database. 我对您的应用程序的总体结构不是很清楚,但是这是一个非常简单的Express应用程序,可以将新类插入数据库。

var express = require('express');
var bodyParser = require('body-parser');

var mongodb = require('mongodb');
var app = express();
app.use(bodyParser.json());

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/school", function(err, database) {
  if(err) throw err;

  db = database;

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

app.post('/class', function(req,res) {
  var collection = db.collection('classes');
  var newClass = req.body;
  console.log(req.body);
  collection.insert(newClass);
  res.json(newClass);
});

In your model change it to: 在您的模型中将其更改为:

module.exports.createNewClass = function(newClass, callback){
      Class.collection.insert(newClass, callback);
};

Check that "Class" should be schema model object. 检查“类”应为架构模型对象。

  module.exports.createNewClass = function(newClass, callback){
      new Class(newClass).save(callback);
    };

It's the basic mongoose way. 这是基本的猫鼬方式。 In mongoose we use "insert" to multiple documents but you can also use insert for single document. 在猫鼬中,我们对多个文档使用“插入”,但是您也可以对单个文档使用插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM