I am currently trying to retrieve certain objects from a mongoDB database using Mongoose.
For some reason I cant filter by the field "provider" that i assigned to my object, but i can filter by the "date" field.
This works perfectly:
const logs = await ActionLog.find({ date:{ $gt: initialDate, $lt: finishDate}});
if(logs.length == 0){
res.status(204);
res.json({message:"No matches for this search"});
}else
res.send(logs);
but this doesn't, it just brings me all of the elements saved:
const logs = await ActionLog.find({ provider:"example" } );
Some of the elements have the field "provider" and some of them don't, but none of them has provider:"example"
[
{
"_id": "6374768bd302cd09838d4c67",
"module": "event approval",
"date": "2022-11-16T05:35:07.252Z",
"__v": 0
},
{
"_id": "637476aad302cd09838d4c69",
"module": "event update",
"date": "2022-11-16T05:35:38.798Z",
"__v": 0
},
{
"_id": "6374768bd302cd09838d4c11",
"module": "sale",
"provider": "prueba",
"date": "2022-11-20T05:35:07.252Z",
"__v": 0
}
]
The problem was my model didn't have "provider" in it.
Blockquote s "provider" on your mongoose model? I havent use mongoose in a while but I think I recall that for it to query on a field it must actually be on your model. I might be remembering this wrong though. –
Sello Mkantjwa
Once i added "provider" to the model it worked.
Related
Im looking for a condition in Mongoose that allows me to find all the users except the ones that haves the role 'Admin':2000. Mind that the admin users also has anothers roles, like "User" and "Editor", like this:
{
"name": "John Doe Admin",
"roles": {
"Admin": 555,
"Editor": 556,
"User": 557
}
}
In the comments is the answer:
.find({ 'roles.Admin': { $ne: 2000 } })
So i am Making a Simple Forum app and ive made a user and post Models but what happens is as i make post mapped to a user when i get back User Data it Contains posts array containing references to their Ids but Its being Empty
{
"success": true,
"users": [
{
"_id": "625c13d8d5aeaa89c3d05f25",
"name": "Atrec",
"email": "atrec#gmail.com",
"posts": [],
"createdAt": "2022-04-17T13:19:20.795Z",
"__v": 0
},
{
"_id": "625c151165d9934d6570e025",
"name": "trial",
"email": "tial#ccc.com",
"posts": [],
"createdAt": "2022-04-17T13:24:33.273Z",
"__v": 0
}
]
}
even if i am Creating Posts they are not getting added to the posts (reference) array so like how do i do it Can you just tell me or refer to something ??? Ive been doing this all day
I have an array of MongoDB Ids like this:
networks = ["5e1cfabb61e9314617fe2db5", "5e1cfbbbe519704860d9a720", "5e1cfbdd4ab5514888b4c6eb"]
I need to push in a new array all documents (the full object) from my database that matches every entry of networks array.
So I want a new like, lets say peopleNetworks to be like this:
`peopleNetworks = [
{
"_id": "5e1cfabb61e9314617fe2db5",
"name": "Facebook",
"createdAt": "2020-01-13T23:18:19.593Z",
"updatedAt": "2020-01-13T23:18:19.593Z",
"__v": 0
},
{
"_id": "5e1cfbbbe519704860d9a720",
"name": "Instagram",
"createdAt": "2020-01-13T23:22:35.057Z",
"updatedAt": "2020-01-13T23:22:35.057Z",
"__v": 0
},
{
"_id": "5e1cfbdd4ab5514888b4c6eb",
"name": "Vero",
"createdAt": "2020-01-13T23:23:09.501Z",
"updatedAt": "2020-01-14T00:00:05.458Z",
"__v": 0
}
]`
I tried to filter my collection using the networks array like this:
`const peopleNetworks = [];
const storedNetworks = await Network.find();
storedNetworks.filter(network => { networks.forEach(id =>
{
if (id === network._id) peopleNetworks.push(network);
})
);`
But it doesn't work.
I think the proper way to do this is by chaining the filter after .find() but I messed up when I tried.
You should to use $in operator. Something like
await Network.find({ _id: { $in: networks } });
This should return you the desired documents and you don't have to fetch all and then filter
You can use $in operator of mongodb with find
const storedNetworks = await Network.find({"_id":{"$in":networks}});
I'm saving an account schema, and nesting it in a User schema with Mongoose, MongoDB, and Node.
Save works fine, but when I look at the saved object JSON, I only see the objectId for the nested schema, and not it's keys, and values.
How can I save the nested schema, so that when I look at the User obj, I see the
all the nested schema object's keys, and values?
[
{
"account": [
"5ac6ed27ed8b4bcbdcfa572b"
],
"createdAt": "2018-04-06T03:44:39.388Z",
"updatedAt": "2018-04-06T03:44:39.388Z",
"_id": "5ac6ed27ed8b4bcbdcfa572d",
"userId": "test20#gmail.com",
"__v": 0
}
]
I'd like it to look like this:
[
{
"account": [
"key": "value",
],
"createdAt": "2018-04-06T03:44:39.388Z",
"updatedAt": "2018-04-06T03:44:39.388Z",
"_id": "5ac6ed27ed8b4bcbdcfa572d",
"userId": "test20#gmail.com",
"__v": 0
}
]
Note: Edits below where I tried this directly using mongo shell and correct collection names, but still the same issue.
I am currently trying to learn Node and Mongodb. I am looking to understand how to add one document with another in a query. All the documentation points back to $lookup.
I have the two following models set up, which both work perfectly on their own
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
var CommentSchema = new Schema({
creator_id : { type: String, ref: 'Bear' },
comment: String
});
module.exports = mongoose.model('Comment', CommentSchema);
I will omit other set up details and get straight to the queries.
When I run Bear.find() I get the expected result...
[
{
"_id": "585887a29b7915f437742b88",
"name": "new bear",
"__v": 0
}
]
When I run Comment.find() I get the expected result...
[
{
"_id": "585887ae9b7915f437742b89",
"creator_id": "584de876238179030d7d7916",
"comment": "yoyoyo",
"__v": 0
},
{
"_id": "585887e09b7915f437742b8a",
"creator_id": "585887a29b7915f437742b88",
"comment": "ok lets give this a go",
"__v": 0
}
]
Note the creator_id in the second comment is the same as the _id in the bear result.
I then run
Bear.aggregate([
{
$lookup: {
from: "Comment",
localField: "_id",
foreignField: "creator_id",
as: "comments"
}
}
], function (err, bears) {
if (err)
res.send(err);
res.json(bears);
});
and get the following:
[
{
"_id": "585887a29b7915f437742b88",
"name": "new bear",
"__v": 0,
"comments": []
}
]
I was hoping the following would appear:
[
{
"_id": "585887a29b7915f437742b88",
"name": "new bear",
"__v": 0,
"comments": [
{
"_id": "585887e09b7915f437742b8a",
"creator_id": "585887a29b7915f437742b88",
"comment": "ok lets give this a go",
"__v": 0
}
]
}
]
I cant understand in this situation how it would know what "Comment" is referring to.
EDIT: From the documentation I can see the from field says: Specifies the collection in the same database to perform the join with. The from collection cannot be sharded.
EDIT 2: In mongoshell I have ran the following queries and their results, as you can see the same issue is still appearing even with the correct collection name, however I can now see ObjectId() may be the issue...
> show collections
bears
comments
> db.bears.find();
{ "_id" : ObjectId("585887a29b7915f437742b88"), "name" : "new bear", "__v" : 0 }
> db.comments.find();
{ "_id" : ObjectId("585887ae9b7915f437742b89"), "creator_id" : "584de87623817903
0d7d7916", "comment" : "yoyoyo", "__v" : 0 }
{ "_id" : ObjectId("585887e09b7915f437742b8a"), "creator_id" : "585887a29b7915f4
37742b88", "comment" : "ok lets give this a go", "__v" : 0 }
> db.bears.aggregate([ { $lookup: { from: "comments", localField: "_id", foreign
Field: "creator_id", as: "comments" } } ]);
{ "_id" : ObjectId("585887a29b7915f437742b88"), "name" : "new bear", "__v" : 0,
"comments" : [ ] }
whenever you'r using $lookup, you must add an extra "s" in "from" field.
for example:
if your table name is
"register"
then you have to write
"registers"
Note: at the time of $lookup only
I resolved this. There were two issues.
The Bear Schema _id is actually an ObjectID() so it wasnt comparing the two correctly.
I misunderstood what collection names were and so Comment would not have been recognised.
Solution:
When creating the Comment Model I used Schema.ObjectId
var CommentSchema = new Schema({
creator_id : { type: Schema.ObjectId, ref: 'Bear' },
comment: String
});
When doing the query I used comments instead of Comment as this was the collection named Mongoose created.
Bear.aggregate([
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "creator_id",
as: "comments"
}
}