MongoClient.Schema不是构造函数

时间:2018-01-08 10:27:22

标签: node.js angular express mean-stack

我创建了一个名为session.js的模型。我使用Angular 4处理MEAN堆栈应用程序,我遇到了下面的错误。

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

var schema = new MongoClient.Schema({

        name : String,
        description : String,
        fromDate : Date,
        toDate : Date
})

var Session = MongoClient.model('session',schema);

module.exports = Session;

代码给出了以下错误:

var schema = new MongoClient.Schema({

              ^
TypeError: MongoClient.Schema is not a constructor

有人可以建议我如何使用MongoClient创建上面的模式吗?

2 个答案:

答案 0 :(得分:0)

您需要使用collections

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/YOUR_DB";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  const data = { name: "Company Inc", description: "..." };

  db.collection("datas").insertOne(data, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
    db.close();
  });
});

如果要创建架构,可以使用ODM,如Mongoose

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
  name : String,
  description : String,
  fromDate : Date,
  toDate : Date
});

答案 1 :(得分:0)

您正在尝试使用不存在的函数!

您正在使用mongodb npm而MongoClient没有.Schema

也许您正在使用MongoDB

来驱使Mongoose ODM驱动程序