How will I select a particular object from the array of objects in the mongoose schema? - express

var mongoose = require("mongoose");
// schema setup
var productSchema = new mongoose.Schema({
type:{
type:String,
required:[true,'a product must have a type']
},
sId:String,
image:String,
products:[{
name:String,
image:String,
price:Number
}]
});
module.exports = mongoose.model("Product",productSchema);
I have made my mongoose schema like this. Now I just want to access a particular object from the array of objects named 'products' using a mongoose query.
Can anyone please tell me how can i do this?? I'll be soo grateful.

You need something like this:
db.collection.find({
"products.name": "name"
},
{
"products.$": 1
})
With this query you will find the product object whose name field is 'name'. Afther that, with the positional operator $ only the matching is returning.
Mongo playground example here
Edit: Note that this query will return multiple subdocuments if exists multiple documents with the array object matching. To filter for a unique element you have to indicate another unique field like this:
db.collection.find({
"sId": "1",
"products.name": "name"
},
{
"products.$": 1
})
Edit to explain how to use find using mongoose.
You can use find or findOne, but the query itself will be the same.
This is pretty simple. You need to use your model described in the question, so the code is somthing like this:
var objectFound = await YourModel.findOne({
"products.name": "name"
},
{
"products.$": 1
})
Where YourModel is the schema defined.

Related

Can I refer to the Row/Document internal variables when filtering in Prisma?

How can I use row/document variables in filters and sorting?
As you know in SQL we can filter on joins beside the foreign key Something like this
Select * From A LEFT JOIN B on A.key = B.foriegnKey AND B.key IN A.currentSelection
or even in mongo lookup
collection('A').aggregate([{
$lookup: {
from: "B",
localField: "key",
foreignField: "foreignKey",
let: { A_currentSelection: "$currentSelection" },
pipeline: [{
$match: {
$expr: { $in: ["$key", "$$A_currentSelection"] }
}
}],
as: "matches"
}
},
])
But you can't do the following in Prisma
prisma.A.findMany({
include: {
B: {
where: {
'$A.currentSelection': {
has: "$B.key"
}
}
}
}
})
Regardless of the query itself, the idea is that I can access the current row/document variables in the query, I also know that I can modify the structure of the database to get around these kinds of issues but the database is already structured in a specific manner that might break some parts of the code and it's also not viable to change the structure just because Prisma is not lacking in this part.
At first, I was using a raw query to get around this and know I've created more complex relationships in the schema to fix this in Prisma in this case, but if anyone knows a more elegant solution then I'd be grateful

TypeORM relationquerybuilder of remove with Not(IsNull()) not removing anything

Good day everyone,
I ran into a strange problem with typeORM. I have a many-to-many relation on Offer with User named pending, which creates a table offer_pending_user that looks like:
userId
offerId
0
1
1
0
I basically want to completely clear this table. I tried to achieve this by using the RelationQueryBuilder like follows:
await Offer.createQueryBuilder()
.relation("pending")
.of({ id: Not(IsNull()) }) //offer id
.remove({ id: Not(IsNull()) }); //user id
For some reason. It does not clear the offer_pending_user table at all. The query that it is executing looks like:
DELETE FROM "offer_pending_user" WHERE ("offerId" = ? AND "userId" = ?) -- PARAMETERS:
[{
"_type":"not",
"_value": {
"_type":"isNull",
"_useParameter":false,
"_multipleParameters":false
},
"_useParameter":true,
"_multipleParameters":false
},{
"_type":"not",
"_value": {
"_type":"isNull",
"_useParameter":false,
"_multipleParameters":false
},
"_useParameter":true,
"_multipleParameters":false
}]
I would like to use this RelationQueryBuilder, and would like to know what I'm missing here.

BookshelfJS - 'withRelated' through relational table returns empty results

I've been trying to structure the relations in my database for more efficient querying and joins but after following the guides for '.belongsToMany', '.through' and '.belongsTo' I'm now getting empty results.
I've got a Sound model and a Keyword model which I want to model with a many-to-many relationship (each Sound can have multiple Keywords, and each Keyword can be related to multiple sounds). Based on the documentation '.belongsToMany' would be the relation to use here.
I've set up my models as follows, using a 'sound_keyword' relational table/SoundKeyword relational model (where each entry has it's own unique 'id', a 'soundID', and a 'keywordID'):
var Sound = bookshelf.Model.extend({
tableName: 'sounds',
keywords: function () {
return this.belongsToMany(Keyword, 'sound_keyword', 'id', 'id').through(SoundKeyword, 'id', 'soundID');
},
});
var Keyword = bookshelf.Model.extend({
tableName: 'keywords',
sounds: function () {
return this.belongsToMany(Sound, 'sound_keyword', 'id', 'id').through(SoundKeyword, 'id', 'keywordID');
}
});
where:
var SoundKeyword = bookshelf.Model.extend({
tableName: 'sound_keyword',
sound: function () {
return this.belongsTo(Sound, 'soundID');
},
keyword: function () {
return this.belongsTo(Keyword, 'keywordID');
}
});
From what I've read in the docs and the BookshelfJS GitHub page the above seems to be correct. Despite this when I run the following query I'm getting an empty result set (the Sound in question is related to 3 Keywords in the DB):
var results = await Sound
.where('id', soundID)
.fetch({
withRelated: ['keywords']
})
.then((result) => {
console.log(JSON.stringify(result.related('keywords')));
})
Where am I going wrong with this? Are the relationships not set up correctly (Possibly wrong foreign keys?)? Am I fetching related models incorrectly?
Happy to provide the Knex setup as needed.
UPDATED EDIT:
I had been using the Model-Registry Plugin from the start and had forgotten about it. As it turns out, while the below syntax is correct, it prefers syntax similar to the following (i.e. lowercase 'model', dropping the '.extends' and putting model names in quotes):
var Sound = bookshelf.model('Sound',{
tableName: 'sounds',
keywords: function () {
return this.belongsToMany('Keyword', 'sound_keyword', 'soundID', 'keywordID');
},
});
var Keyword = bookshelf.model('Keyword',{
tableName: 'keywords',
sounds: function () {
return this.belongsToMany('Sound', 'sound_keyword', 'keywordID', 'soundID');
}
});
Hope this can be of help to others.
Seems like removing the '.through' relation and changing the IDs in the '.belongsToMany' call did the trick (as below), though I'm not entirely sure why (the docs seem to imply belongsToMany and .through work well together - possibly redundant?)
var Sound = bookshelf.Model.extend({
tableName: 'sounds',
keywords: function () {
return this.belongsToMany(Keyword, 'sound_keyword', 'soundID', 'keywordID');
},
});
var Keyword = bookshelf.Model.extend({
tableName: 'keywords',
sounds: function () {
return this.belongsToMany(Sound, 'sound_keyword', 'keywordID', 'soundID');
}
});
I did try my original code with soundID and keywordId instead of 'id' (as below), but without the .through relation and that gave the same empty results.

Sequelize Querying with Op.or and Op.ne with same array of numbers

I'm having trouble getting the correct query with sequelize.
I have an array representing ids of entries lets say its like this -
userVacationsIds = [1,2,3]
i made the first query like this
Vacation.findAll({
where: {
id: {
[Op.or]: userVacationsIds
}
}
})
.then(vacationSpec => {
Vacation.findAll({
where:{
//Here i need to get all entries that DONT have the ids from the array
}
}
})
I can't get the correct query as specified in my code "comment"
I've tried referring to sequelize documentation but i can't understand how to chain these queries specifically
Also tried an online converter but that failed too.
Specified the code i have above
So i just need some help getting this query correct please.
I eventually expect to get 2 arrays - one containing all entries with the ids from the array, the other containing everything else (as in id is NOT in the array)
I figured it out.
I feel silly.
This is the query that worked
Vacation.findAll({
where: {
id: {
[Op.or]: userVacationsIds
}
}
}).then(vacationSpec => {
Vacation.findAll({
where: {
id: {
[Op.notIn]: userVacationsIds
}
}
})

PouchDB Query like sql

with CouchDB is possible do queries "like" SQL. http://guide.couchdb.org/draft/cookbook.html says that
How you would do this in SQL:
SELECT field FROM table WHERE value="searchterm"
How you can do this in CouchDB:
Use case: get a result (which can be a record or set of records) associated with a key ("searchterm").
To look something up quickly, regardless of the storage mechanism, an index is needed. An index is a data structure optimized for quick search and retrieval. CouchDB’s map result is stored in such an index, which happens to be a B+ tree.
To look up a value by "searchterm", we need to put all values into the key of a view. All we need is a simple map function:
function(doc) {
if(doc.value) {
emit(doc.value, null);
}
}
This creates a list of documents that have a value field sorted by the data in the value field. To find all the records that match "searchterm", we query the view and specify the search term as a query parameter:
/database/_design/application/_view/viewname?key="searchterm"
how can I do this with PouchDB? the API provide methods to create temp view, but how I can personalize the get request with key="searchterm"?
You just add your attribute settings to the options object:
var searchterm = "boop";
db.query({map: function(doc) {
if(doc.value) {
emit(doc.value, null);
}
}, { key: searchterm }, function(err, res) { ... });
see http://pouchdb.com/api.html#query_database for more info
using regex
import PouchDB from 'pouchdb';
import PouchDBFind from 'pouchdb-find';
...
PouchDB.plugin(PouchDBFind)
const db = new PouchDB(dbName);
db.createIndex({index: {fields: ['description']}})
....
const {docs, warning} = await db.find({selector: { description: { $regex: /OVO/}}})