我已经创建了一个AWS帐户,并希望使用MongoDB阿特拉斯与AWS。我下载的唯一依赖项是本地mongodb。
npm install mongodb基于驱动程序的连接字符串来自Nodejs的mongoDB Atlas
var uri = "mongodb+srv://kay:myRealPassword@cluster0.mongodb.net/test";
MongoClient.connect(uri, function(err, client) {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});我认为连接是成功的,因为err参数为NULL。
但是我不知道如何创建集合,如何找到结果,如何插入文档。
我试过这段代码
module.exports.hello = (event, context, callback) => {
var MongoClient = require('mongodb').MongoClient;
var uri = "mongodb+srv://kay:myRealPassword@cluster0.mongodb.net/test";
MongoClient.connect(uri, function(err, client) {
const collection = client.db("test").collection("devices");
collection.insert( { "msg" : "My First Document" } );
var results = client.db("test").collection("devices").find();
console.log(results);
client.close();
callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
});
};但它以JSON格式返回一个巨大的对象(在Windows控制台中),它类似于配置数据(而不是查询结果)
我在本地执行这段代码
sls invoke local --function hello发布于 2018-02-15 12:53:23
一般的想法是检查连接、插入等方面是否有错误。看看这个错误检查:
if (error) return 1;有更复杂的方法,但就您的情况而言,这应该可以完成工作。
这是一个显示脚本外观的示例:
MongoClient.connect(uri, (error, client) => {
if (error) return 1; // Checking the connection
console.log('Connection Successful');
var db = client.db('mydb'); // Your DB
let newDocument = { "msg" : "My First Document" }; // Your document
db.collection('mycollection').insert(newDocument, (error, results) => { // Your collection
if (error) return 1; // Checking the insert
console.log('Insert Successful');
})
db.collection('mycollection')
.find({})
.toArray((error, accounts) => {
if (error) return 1; // Checking the find
console.log('Find Successful');
console.log(accounts);
return 0;
})
})你应该有这样的输出:
Connection Successful
Insert Successful
Find Successful
[ { _id: 5a857dd2c940040d85cbe5f2, msg: 'My First Document' } ]如果您的输出不是这样的,那么丢失的日志将指出错误所在的位置。
https://stackoverflow.com/questions/48806535
复制相似问题