sailsjs在不使用ORM的情况下使用mongodb [英] sailsjs use mongodb without ORM

查看:86
本文介绍了sailsjs在不使用ORM的情况下使用mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用任何ORM的情况下使用mongodb.因此,以下是我连接mongodb的服务.
服务:

I want to use mongodb with sails but without any ORM. So below is my service to connect mongodb.
Service:

//DbService.js

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

    module.exports = {
      db:function(req, res){
        var connect=MongoClient.connect("mongodb:***********").then(function (err, database) {
          if(err) console.log(err);
          else{
            database=database.db('*****');
            return connect;
          }  

        });  
      }
    }

连接后,我已经在控制器中调用它,但是得到TypeError:无法读取未定义的属性'then'.

After connection i have called it in controller, But getting TypeError: Cannot read property 'then' of undefined.

控制器:

//HomeControlelr.js
    module.exports = {
            index:function(req, res){
                DbService.db().then(function(err,db) {
                    console.log(db);
                })
            }
    };

推荐答案

第一个npm i mongodb,因为您需要用new ObjectID(idStr)包装任何ID.

First npm i mongodb because you'll need to wrap any ID's with new ObjectID(idStr).

然后您可以执行以下操作:

Then you can do this:

const collection = Pet.getDatastore().manager.collection(Pet.tableName);
const res = await collection.find({ name: { $regex: /blue/ } });
const dataWithObjectIds = await res.toArray();
const dataWithIds = JSON.parse(JSON.stringify(rawDataArr).replace(/"_id"/g, '"id"'));

我创建了一个辅助函数来为我们做所有这些事情:

I created a helper function to do all of this for us:

/**
 * Use by chaining as if you were acting on a collection. So can use .find .aggregate etc.
 * Returns json searializable data.
 *
 * @param {class} model A model
 * @param {number} cnt - Number of chains on this, so I know when it reached the end
 */
function nativeMongoQuery(model, cnt) {

  const collection = model.getDatastore().manager.collection(model.tableName);

  let callCnt = 0;

  let req;

  const proxy = new Proxy({}, {
    get: (_, method) => (...args) => {

      if (!req) req = collection[method](...args);
      else req = req[method](...args);

      callCnt++;

      if (callCnt === cnt) {
        return (async function() {
          const rawDataArr = await req.toArray();
          return JSON.parse(JSON.stringify(rawDataArr).replace(/"_id"/g, '"id"'));
        })();
      } else {
        return proxy;
      }
    }
  });

  return proxy;

}

module.exports = nativeMongoQuery;

我不喜欢JSON解析和字符串化以及全局替换.但是,如果我不进行字符串化处理,那么mongo _id都是ObjectId.

I don't like the JSON parse and stringify and global replace. But if I don't do the stringify, then mongo _id's are all ObjectIds.

像这样使用它:

const { ObjectId } = require('mongodb');

function makeObjectId(id) {
   return new ObjectId(id);
}

const ownerIds = ['5349b4ddd2781d08c09890f4', '5349b4ddd2781d08c09890f5']
const ownerObjectIds = ownerIds.map(makeObjectId);
await nativeMongoQuery(Pet, 2).find({ owner: { $in: ownerObjectIds } }).sort({ dueAt: 1 });

这里是另一个示例:

const mostRecentlyCreatedPets = await nativeMongoQuery(Pet, 1).aggregate([
  { $match: { owner: { $in: ownerObjectIds } } },
  { $sort: { createdAt: -1 } },
  { $limit: 1 }
]);

cnt参数告诉您在那里链接了多少东西.

The cnt argument tells you how many things you have chained off of there.

这篇关于sailsjs在不使用ORM的情况下使用mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆