使用 mongoclinet 的 Node Js 休息服务

Node Js rest services using mongoclinet

我是一名初级开发人员,我正在 Azure 上使用 Node JS、Express、MongoDB 开发 REST 服务。 在我开发的第一个休息服务中,我总是使用 Mongoose 进行开发,但现在我发现在 Cosmos DB 上使用 mongoose 存在一些问题。 Cosmos DB 连接 Node 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}});
});
});

现在,当我尝试 运行 应用程序 ai 时收到此错误: mongoClient.Schema 不是函数 我不知道我的代码是否可以? 我该如何解决?

谢谢 最佳

我认为你在混淆概念。 您正在尝试做的是使用 MongoClient 创建一个 MongoDB 模式,它不支持此功能。 为此使用猫鼬: 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 教程。