From the manual I understand the following instruction...
Person.find({ name: "Jack" }, function (err, people) {
// finds people with name='Jack'
});
I would like to find two people, "Jack" and "Jill". This is obviously incorrect, but something like...
Person.find({ name: "Jack" AND name: "Jill" }, function (err, people) {
// finds all people with name='Jack' and name ='Jill'
});
Person.find({or:[{name: 'Jack'}, {name: 'Jill'}]}, function(err, res) {
});
This should work fine:
Person.find({ name: ["Jack", "Jill"] }, function (err, people) {
// finds all people with name='Jack' and name ='Jill'
});
Related
Im implementing a mongodb search.
The search performs a find on field values:
[{
value: "my.string.here"
}, {
value: "my other here"
}{
...
}]
When i enter "my" both entries are found. What have my query to look like to ignore the dots on the first entry? So when i enter "my string" the first element gets returned?
Actually it works only when i enter "my.string" which is not nice.
let limit = Number(req.query.limit || 100);
let skip = Number(req.query.skip || 0);
collection.find({
$or: [{
value: new RegExp(req.body.search, "gi")
}, {
tags: {
$in: req.body.search.split(",").map((val) => {
return new RegExp(val, "gi")
})
}
}]
}).skip(skip).limit(limit).toArray((err, result) => {
if (err) {
res.status(500).json(err);
} else {
res.status(200).json(result);
}
});
EDIT:
A solution could look like this:
let query = {
$or: [{
name: new RegExp(req.body.search, "gi")
}, {
tags: {
$in: req.body.search.split(",").map((val) => {
return new RegExp(val, "gi")
})
}
}, {
name: new RegExp(req.body.search.split(' ').join('.'), "gi")
}, {
name: new RegExp(req.body.search.split(' ').join('_'), "gi")
}, {
name: new RegExp(req.body.search.split(' ').join('-'), "gi")
}]
};
But i find it ugly and not elegant. Is there a better way to do this ?
I try to build a test backend with express.
And got a problem that i cannot seem to overcome.
Trying to give the query object $regex param a value from the req.query.name. But it only returns an empty array. When i console.log(laptopName) it outputs the right value that is being given as a query param.
If i just replace $regex: laptopName with a concrete value $regex: 'vivobook' i do get results.
With $regex: laptopName console.log looks like this { name: { '$regex': '"vivobook"', '$options': 'i' } }
With $regex: 'vivobook' console.log looks like this: { name: { '$regex': 'vivobook', '$options': 'i' } }
app.get("/api/v1/laptops", (req, res) => {
MongoClient.connect(mongo_url, { useNewUrlParser: true }, (err, client) => {
const db = client.db("laptop_backend");
const collection = db.collection("laptops");
let laptopName = req.query.name;
let query = {
name: {
$regex: laptopName,
$options: 'i'
}
};
collection
.find(query)
.toArray()
.then(response => res.status(200).json(response))
.catch(err => console.error(err));
});
});
Try getting laptop name directly from params such as
let { name } = req.query;
let query = {
name: {
$regex: name,
$options: 'i',
}
};
if you are to modify completely i suggest changing code without promise.
app.get("/api/v1/laptops", async (req, res) => {
try {
const client = await MongoClient.connect(mongo_url, { useNewUrlParser: true });
const db = client.db('laptop_backend');
const collection = db.collection('laptops');
const { name } = req.query;
const query = {
name: {
$regex: name,
$options: 'i',
},
};
const result = await collection.find(query);
res.status(200).json({ result });
} catch (e) {
console.log(e);
res.status(400).json({ error: true });
}
});
I have a dataset like this:
{
_id: ObjectId("5b51a905c2ee6718204e945d"),
post: "hello apple"
},
{
_id: ObjectId("5b51a905c2ee6718204e945e"),
post: "he is going to buy a cup of coffee"
}
Now I would like to create a search, for that, I wrote the query i.e.
db.Collection.find({
post: { $regex: req.body.searchterm, $options: "i" }
}).then(data => {
console.log(data);
})
.catch(error => {
console.log(error)
});
This is working fine. Suppose I search "a" then it will return first and second object. But I want that result where a is individually written, not comes on between character.
I want only the second object return where a is written alone, but not comes on the first object because a is present on apple.
Any Suggestion on how I can enhance this. Any suggestion is really appreciated.
As Sergio suggested, use regex \ba\b. It will match only separate a
Regex online demo
try this :
var expression = new RegExp("(?=.*\\b" +req.body.searchterm + "\\b)")
db.Collection.find({
post: { $regex: expression, $options: "i" }
}).then(data => {
console.log(data);
})
.catch(error => {
console.log(error)
});
I'm trying to do a custom url.
More specifically, what I've already done is:
mypage.com/details/1
What I'd like to do is:
mypage.com/details/john-doe
Of course, I want exactly the same behavior as now, with the sole difference being a custom string instead of id
Here's my DS model
App.Images.FIXTURES = [
{
id:1,
name: "John",
lastName: "Doe",
age: 25,
customUrl: "john-doe"
},
{
id:2,
name: "John",
lastName: "Doe",
age: 31,
customUrl: "john-doe1"
}];
*Note the customUrl attribute which is unique.
My routes:
App.Router.map(function(){
this.resource("details", {path: 'details/:image_id'});
});
And the according html:
{{#linkTo 'details' this}}The details{{/linkTo}}
What are my options? Putting "this" in html automatically grabs the ID. I tried this.customUrl with no luck (I get the "undefined" value in the url).
Thank you for your help!
you can override serialize in router to return customUrl instead of id
App.DetailsRoute = Ember.Route.extend({
// ....
serialize: function(model) {
return { details_id: model.get('customUrl') };
}
});
My code is quite simple (Client Side):
Record.Router.map(function () {
this.resource('main', { path: '/' });
});
Record.MainRoute = Ember.Route.extend({
model: function () {
var response = Record.Rank.find();
console.log(response.get('name'));
console.log(response);
return Record.Rank.find();
}
});
My model:
Record.Rank = DS.Model.extend({
id: DS.attr('integer'),
rank: DS.attr('integer'),
content: DS.attr('string')
});
I use RESTadapter:
Record.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.reopen({
namespace: 'recordApp'
})
});
My Server side code (PHP):
<?php
namespace RecordContainer;
echo '{"rank":
{
"id": "1",
"rank": "2",
"content": "walla"
}
}';
I expect to something after I issue Record.Rank.find() but my console.log(response.get('name')) logs undefined and the second console.log(response) show the following, no information about echo from server inside:
How do I see the response from the server, in Ember?
1st: Calling find on a DS.Model without any parameters, i.e. Record.Rank.find(), is equivalent to sending a findAll() request to your server. In other words, it should fetch all Record.Rank. Therefore ember-data expects an array in the response of the format:
{
"ranks":[
{
"id": "1",
"rank": "2",
"content": "walla"
},
{
"id": "2",
"rank": "5",
"content": "foo"
}
]
}
2nd: Even if the response from the PHP was correct (as described above), console.log(response.get('name')); would probably return undefined since the request is not yet completed and the record(s) are not available. If you really want to access the records loaded into the store you need to place your code into a Promise resolve callback:
Record.MainRoute = Ember.Route.extend({
model: function () {
var response = Record.Rank.find();
response.then(function(ranks) {
console.log(ranks.getEach('name'));
});
return response;
}
});