【问题标题】:Node Js rest services using mongoclinet使用 mongoclinet 的 Node Js 休息服务
【发布时间】:2018-09-10 09:38:08
【问题描述】:

我是一名初级开发人员,我正在使用 Azure 上的 Node JS、Express、MongoDB 开发一个 REST 服务。 在我开发的第一个休息服务中,我总是使用 Mongoose 进行开发,但现在我发现在 Cosmos DB 上使用 mongoose 存在一些问题。 Cosmos DB 连接节点 js 与 MongoDb mongoclient 一起使用。我已经创建了一个 db.js 文件:

var mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://dbname:xxxxxxxx@dbname.documents.azure.com:10255/?ssl=true", function (err, db) {
db.close();
});

module.exports = mongoClient;

我已经定义了一个模型:

var mongoClient = require('../config/db.js');


var ProfileSchema = mongoClient.Schema({
companyName: { type: String, required: true },
firstname: {type: String, required: true},
address: {type: String, required: true},
city: {type: String, required: true},
state: {type: String, required: false},
postalcode: {type: String, required: true},
country: {type: String, required: true},
telephone: {type: String, required: true},
email: {type: String, required: true}
});
mongoClient.model('Profile', ProfileSchema);

module.exports = mongoClient.model('Profile');

这是我的路由器:

var Profile = require('../models/Profile');


router.get('/profile', function(req,res){
Profile.find({}, (err, profile) => {
    if (err) {
        console.log(err);
        return res.status(400).send({ status: 'ko', data: {msg: err.message }});
    }
    res.status(200).send({status: 'ok', data: {msg: 'List', profile: profile}});
});
});

现在当我尝试运行 app ai 时收到此错误: mongoClient.Schema 不是函数 我不知道我的代码是否正常? 我该如何解决?

谢谢 最好的

【问题讨论】:

    标签: arrays node.js mongodb distinct


    【解决方案1】:

    我认为你在混合概念。 您要做的是使用不支持此功能的 MongoClient 创建 MongoDB Schema。 为此使用猫鼬: https://mongoosejs.com/docs/guide.html

    MongoClient 是 MongoDB 的基本驱动程序,我认为您不想直接使用它。

    另外,在您的模型文件中,您正在使用这个:

    var mongoClient = require('../config/db.js');
    

    我不知道你在文件 db.js 中有什么,但我认为你没有在那里实现自定义 Schema() 函数,这就是你收到错误“mongoClient.Schema is not a function”的原因. 为实现此目的,请避免直接使用 MongoClient,并查看一些 Mongoose 教程。

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 2013-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多