mongoose: myModel.find always return subdocument - find

var myschema = new Schema({
name: {type:String, default:'fullname'},
subdoc: {
day1: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
day2: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}
}
});
var mymodel = Mongoose.model('mytest',myschema);
//mongoose 3.5.6: find
mymodel.find({},{'name'}, function(err,docs){
logger.info("---> " + docs);
});
results:
---> { _id: 512da190ba48050f2e000001, **subdoc: {}**, name: 'fullname' }
Only name field is requested to be returned, but this function always returns subdoc: {}. Can someone explain this?
use mongodb shell, it looks fine
db.mytests.find({},{"name":1})
{ "_id" : ObjectId("512da190ba48050f2e000001"), "name" : "fullname" }
Then I change the model to:
var myschema = new Schema({
name: {type:String, default:'fullname'},
subdoc: [
day1: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
day2: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}
] // **note: not {} here**
})
use the same mongoose api find, the result is just what I expected:
--->{ _id: 512da46fffebd24b30000002, name: 'fullname' }
My questions is: Why field 'subdoc' is returned with the former schema?

According to the docs, it appears as if you are a little bit off.
Example:
// name LIKE john and only selecting the "name" and "friends" fields, executing immediately
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
With that, I would do something like this:
myModel.find( {}, 'name', callback);
Edit
To address your comments: In mongodb console, the proper way to format it would be {'name':1, 'friend':1}. Using:
db.collection.find({}, {'name friend'})
will throw an error. To do this properly, you would do:
db.collection.find({}, {'name':1, 'friend':1})
However, if you prefer this way of field selection, mongoose does allow you to do that as well.
myModel.find({}, {'name':1, 'friend': 1}, callback);
See: API Docs

Related

Mongoose check value from other schema while findAndUpdate

Am I able to check a value from other mongo schema while findAndUpdate?
Example:
Schema 1:
{ _id: 'myId1', name: 'test' }
Schema 2:
{ _id: 'myId2', name: 'test-rest', connectedId: [ 'myId1' ] }
Now I want to check if connectedId has value name while updating
await MongoModel.findOneAndUpdate(
{
_id: "myId",
connectedId: { connectedValue.name === 'test' } // Now I want check if value from this connectedId has a value equal to my value
},
{
name: "changeName"
}
)
EDIT: I completely overlooked that you also wanted to update the referenced document. I will howeever leave this answer in case someone else finds it useful.
You should checkout populate from Mongoose documentation. You can add references to other models like this when defining your schema:
connected: [{ type: Schema.Types.ObjectId, ref: 'OtherModelName' }]
OtherModelName should match with however you name your other model when calling mongoose.model('OtherModelName', yourSchema); After that, you can populate the field with some conditions. This example is from the aforementioned documentation:
Story.
find().
populate({
path: 'fans',
match: { age: { $gte: 21 } },
// Explicitly exclude `_id`
select: 'name -_id'
}).
exec();
In your case, it would be something like
YourModel
.find()
.populate({
path: 'connected',
match: {name: 'test'}
})
.exec();

Use GraphQL Query to get results form MongoDB after aggregation with mongoose

so i have following problem.
I have a mongoDB collection and a corresponding mongoose model which looks like this.
export const ListItemSchema = new Schema<ListItemSchema>({
title: { type: String, required: true },
parentId: { type: Schema.Types.ObjectId, required: false },
});
export const TestSchema = new Schema<Test>(
{
title: { type: String, required: true },
list: { type: [ListItemSchema], required: false },
}
);
As you can see, my TestSchema holds an Array of ListItems inside -> TestSchema is also my Collection in MongoDB.
Now i want to query only my ListItems from a Test with a specific ID.
Well that was not that big of a problem at least from the MongoDB side.
I use MongoDB Aggregation Framework for this and call my aggregation inside a custom Resolver.
Here is the code to get an array of only my listItems from a specific TestModel
const test = TestModel.aggregate([
{$match: {_id: id}},
{$unwind: "$list"},
{
$match: {
"list.parentId": {$eq: null},
},
},
{$replaceRoot: {newRoot: "$list"}},
]);
This is the result
[ { _id: randomId,
title: 't',
parentId: null },
{ _id: randomId,
title: 'x'
parentId: null
} ]
The Query to trigger the resolver looks like this and is placed inside my Test Type Composer.
query getList {
test(testId:"2f334575196fe042ea83afbf", parentId: null) {
title
}
}
So far so good... BUT! Ofc my query will fail or will result in a not so good result^^ because GraphQL expects data based on the Test-Model but receives a completely random array.
So after a lot of typing here is the question:
How do i have to change my query to receive the list array?
Do i have to adjust the query or is it something with mongoose?
i really stuck at this point so any help would be awesome!
Thanks in advance :)
I'm not sure if I understood your issue correctly.
In your graphql, try to leave out exclamation mark(!) from the Query type.
something like :
type Query {
test: TestModel
}
instead of
type Query {
test: TestModel!
}
then you'll get the error message in console but still be able to receive any form of data.

How to define mongoose schema for nested documents

I need to define the mongoose schema for for nested documents which is given below.
Documents:
"Options":[{"Value":["28","30","32","34","36","38","40","42","44","46"],"_id":{"$oid":"5de8427af55716115dd43c8f"},"Name":"Size"},{"Value":["White"],"_id":{"$oid":"5de8427af55716115dd43c8e"},"Name":"Colour"}]
I was declaring like below but its not working.
const Product = new Schema(
{
Options: [{ value: { _id: ObjectId, Name: String } }]
},
{
timestamps: {
createdAt: "createdAt",
updatedAt: "updatedAt"
},
collection: "products"
}
);
Here I need the schema where if i will directly add/update the same document then it will be added.
You need to modify your schema like this :
{
Options: [ new Schema ({ value: [...], _id: Schema.Types.ObjectId, Name: String })]
}
This is the way to create an array of subdocuments with Mongoose. If you don't use the "new Schema" key words, you are actually creating a field with type "Mixed", which needs a different way to handle updates.
You can also omit the _id, it should be added automatically.
You can find more information on subdocument on this page :
https://mongoosejs.com/docs/subdocs.html
...and on mixed type fields : https://mongoosejs.com/docs/schematypes.html#mixed
...which will explain shortly the problem.
{
Options: [ new Schema ({ _id: mongoose.Types.ObjectId(),value: [String], Name: String } })]
}

fetching documents based on nested subdoc array value

I'm trying to get all documents in a collection based on a subdocument array values. This is my data structure in the collection i'm seeking:
{
_id: ObjectId('...'),
name: "my event",
members:
[
{
_id: ObjectId('...'),
name: "family",
users: [ObjectId('...'),ObjectId('...'),ObjectId('...')]
},
{
_id: ObjectId('...'),
name: "work",
users: [ObjectId('...'),ObjectId('...'),ObjectId('...')]
}
]
}
I should point out that the schema of these objects are defined like so:
Events:
{
name: { type: String },
members: {type: [{ type: ObjectId, ref: 'MemberGroup' }], default:[] }
}
MemberGroup:
{
name: { type: String },
users: [{type: mongoose.Schema.Types.ObjectId, ref: 'User'}]
}
and of course User is just an arbitrary object with an id.
What i'm trying to fetch: i want to retrieve all events which has a specific user id in its member.users field.
i'm not sure if its event possible in a single call but here is what i've tried:
var userId = new mongoose.Schema.ObjectId('57d9503ef10d5ffc08d6b8cc');
events.find({members: { $elemMatch : { users: { $in: [userId]} } }})
this syntax work but return no elements even though i know there are matching elements (using robomongo to visualize the db)
So after a long search in stackoverflow i came across the good answare here:
MongoDB: How to find out if an array field contains an element?
my query changed to the following which gave me my desired result:
var userId = new mongoose.Schema.ObjectId('57d9503ef10d5ffc08d6b8cc');
events.find({}, {members: { $elemMatch : { users: { $eq: userId} } }})
notice the use of the second find parameter to specify the query limit instead of the first one (which is odd)

OData - Strange index with MongoDB [Mongoose: Cast Error]

I have some MongoDB documents with this schema:
Id: {type: "id", key: true, computed: true, nullable: false},
Name: {type: "string", nullable: false, maxLength: 50}
and these documents are exposed as OData by a small web application (I'm using Express, JayData, and Mongoose).
These are some of those documents:
{ "_id" : ObjectId("5343fd656b9c5c084b8f2a70"), "Name" : "Service74"},
{ "_id" : ObjectId("5343fd656b9c5c084b8f2a6f"), "Name" : "Service73"},
{ "_id" : ObjectId("5343fd656b9c5c084b8f2a6e"), "Name" : "Service72"},
...
If I type this address http://localhost:8080/marketplace/Services('5343fd656b9c5c084b8f2a70') which correspond to Service74 I get this result:
...
<d:Id>NTM0M2ZkNjU2YjljNWMwODRiOGYyYTcw</d:Id>
<d:Name>Service74</d:Name>
...
Of course If I use the Id specified in the result I obtain the same page.
The problem occurs when I try to use the mongoose function findById:
app.post("/addCompare/:id", function(req, res) {
console.log(req.params.id);
Services.findById(req.params.id, function(err, service) {
if(!err) {console.log(service);}
else {console.log(err);}
});
res.send(200);
});
I get this NTM0M2ZkNjU2YjljNWMwODRiOGYyYTcw and then this error:
{ message: 'Cast to ObjectId failed for value "NTM0M2ZkNjU2YjljNWMwODRiOGYyYTU5" at path "_id"',
name: 'CastError',
type: 'ObjectId',
value: 'NTM0M2ZkNjU2YjljNWMwODRiOGYyYTU5',
path: '_id' }
Where am I wrong? Tell me if I miss some other information...
Thanks.
PS: I found a similar problem here Mongoose: Cast to ObjectId failed, but if I change the model definition for Mongoose (in which actually I don't declare the id) by including this definition:
var serviceSchema = mongoose.Schema({
_id: String,
...
nothing changes...
The 5343fd656b9c5c084b8f2a70 is the internal identifier of the entity that is used on the server-side. This value is base64-encoded over OData, this is why you receive NTM0M2ZkNjU2YjljNWMwODRiOGYyYTcw in the Id field. The entity can be easily retrieved by Id by calling atob(req.params.id) on the received Id.