sql >> Databáze >  >> NoSQL >> MongoDB

sailsjs používají mongodb bez ORM

První npm i mongodb protože budete muset všechna ID zabalit do new ObjectID(idStr) .

Pak můžete udělat toto:

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"'));

Vytvořil jsem pomocnou funkci, která to všechno udělá za nás:

/**
 * 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;

Nelíbí se mi JSON parse a stringify a globální nahrazování. Ale pokud neudělám stringify, pak mongo _id jsou všechny ObjectId s.

Použijte jej takto:

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 });

Zde je další příklad:

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

cnt argument vám řekne, kolik věcí jste odtamtud odvázali.



  1. Souhrnná skupina podle data s posunem letního času

  2. Jak funguje parametr arrayFilters v MongoDB

  3. SQLite na Androidu a MongoDB se synchronizací

  4. Manipulace se uvolnit pro neexistující vložený dokument