When I run my http requests in postman, my schema number doesn't show. It shows null.
``const mongoose = require('mongoose');
const OrganisationSchema = mongoose.Schema({
name: String,
yearFounded: Number,
revenue: Number
}, {
timestamps: true
});
module.exports = mongoose.model('Organisations', OrganisationSchema);
{"name": "MadHouse", "yearFounded": "1988", "revenue": "100"}
{
"_id": "5d0d04523668a64609bd20a2",
"name": "Untitled Organisation",
"createdAt": "2019-06-21T16:22:42.974Z",
"updatedAt": "2019-06-21T16:24:29.956Z",
"__v": 0,
"revenue": null,
"yearFounded": null
}
This should be the problem with your insertion or retrieval of data. Just to confirm make revenue and year as required then try inserting.
I just got home and downloaded you project from github, and was able to run it on my machine. And like I said, when the revenue field is sent as a Number, it's works fine.
Here is the JSON on the database:
{
"_id" : ObjectId("5d0d55eb2b177faf109d53e3"),
"name" : "Teste",
"yearFounded" : NumberInt(2019),
"revenue" : 145.8,
"createdAt" : ISODate("2019-06-21T22:10:51.634+0000"),
"updatedAt" : ISODate("2019-06-21T22:10:51.634+0000"),
"__v" : NumberInt(0) }
Try to simulate the same data I sent, and check if you're still getting the same bad behavior.
Related
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.
I'm trying to do a POST to the Strapi API and can't seem to figure out how to attach a 'has and belongs to many' (many to many) relationship.
I've already tried the following body's:
events: ["ID", "ID"]
name: "name"
&
events: [ID, ID]
name: "name"
Which regarding the docs should be right, I think.
There's no error, I get a '200 OK' response. It adds the record but without the relations.
Event.settings.json:
{
"connection": "default",
"collectionName": "events",
"info": {
"name": "event",
"description": ""
},
"options": {
"increments": true,
"timestamps": [
"created_at",
"updated_at"
],
"comment": ""
},
"attributes": {
"name": {
"type": "string"
},
"artists": {
"collection": "artist",
"via": "events",
"dominant": true
}
}
}
Artist.settings.json:
{
"connection": "default",
"collectionName": "artists",
"info": {
"name": "artist",
"description": ""
},
"options": {
"increments": true,
"timestamps": [
"created_at",
"updated_at"
],
"comment": ""
},
"attributes": {
"name": {
"required": true,
"type": "string"
},
"events": {
"collection": "event",
"via": "artists"
}
}
}
I'm using the standard SQLite database, strapi version 3.0.0-beta.13 and tried the request through Postman, HTML & curl.
I would love to know how to attach the relation on POST
Update 23-07:
Did a fresh install of Strapi and now everything is working.
I think it's because your set you ID as a String instead of an Integer
{
events: [1, 2],
name: "My name"
}
And here 1 and 2 are the IDs of events you want to add.
Late reply. Hoping this might help someone!
Right now I am using Strapi v4.3.2 and was facing the same issue. I overcame this by overriding the default core controller for create as explained in official docs. Relations are now visible!
async create(ctx) {
const { data } = ctx.request.body;
const response = await strapi.entityService.create(
"api::collection.collection",
{
data: data,
}
);
return {response}
}
This is (still? again?) a bug in Strapi, see: https://github.com/strapi/strapi/issues/12238
As a workaround you need to add the find-permission to the user / role who is performing the request for the related content type (you want to check first if this is a security issue for your scenario or not - alternatively you might want to try Paratron's approach which is described in the comments).
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"
}
}
I am new to Mongo db/Mongoose, this question is about mongoose and relationships between collections, I know there's a lot of tutorials about how to make this work but still not able to understand an easy way to make this work. I have a two models:
This is the main model:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var CategorySchema = new Schema({
name : String,
info : String,
items : [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});
var itemsSchema = Schema({
name : String,
description : String,
price : Number
});
var Item = mongoose.model('Item', itemsSchema);
module.exports = mongoose.model('Category', CategorySchema);
I need to populate items array inside category collection and create the relationship between the two collections.
When I a post from postman I can see the items array getting created but I am not able to populate the array.
If I do get categories, this is the response:
[
{
"_id": "564120be4123198a1f93feb5",
"name": "Classic",
"info": "this is the info",
"__v": 0,
"items": []
},
{
"_id": "5641220b02968e901f678ff5",
"name": "Classic",
"info": "this is the info",
"__v": 0,
"items": []
}
]
This is the put result to api/categories/
{
"_id": "564120be4123198a1f93feb5",
"name": "test again",
"info": "this is the info",
"__v": 1,
"items": []
}
Desired output:
{
"_id": "564120be4123198a1f93feb5",
"name": "test again",
"info": "this is the info",
"__v": 1,
"items": [
{
"_id": "some id"
"name": "name",
"description": "lorem ipsup"
},
{
"_id": "some id"
"name": "name",
"description": "lorem ipsup"
},
{
"_id": "some id"
"name": "name",
"description": "lorem ipsup"
},
]
}
Even if you've a reference in Category, you should use populate method to inform mongoose that you want him to retrieve the referenced items.
Something like:
var Category = require('./category.model');
Category.find().populate("items");
if you want to populate only one field of item model you can add it ine parameter of populate:
Category.find().populate("items","name");
I don't know what you want to achieve but it seems to me that the other way could be more beneficial (having a reference to category into item model).
I'm using ember rc3 and ember-data 12 (sha e324f0e) (basically the files recommended in the guides). I have 2 models set up as follows:
App.User = DS.Model.extend({
username: DS.attr('string'),
playerType: DS.attr('string'),
cars: DS.hasMany('App.Car')
})
App.Car = DS.Model.extend({
name: DS.attr('string'),
thumb: DS.attr('string'),
user: DS.belongsTo('App.User')
})
The json returned is
{
"cars": [
{
"id": "50ace47234fa7557403e7f02",
"name": "Dodge Charger SRT8",
"thumb": "/static/images/carthumbs/18331.png",
"user_id": "502a754b34fa75280c000a7e"
},
{
"id": "508668cc34fa753b78784ca2",
"name": "BMW M3 Coup\u00e9",
"thumb": "/static/images/carthumbs/23250.png",
"user_id": "502a754b34fa75280c000a7e"
},
{
"id": "50c7545334fa750ab8cb3ac2",
"name": "BMW Z4 M Coup\u00e9",
"thumb": "/static/images/carthumbs/7618.png",
"user_id": "502a754b34fa75280c000a7e"
},
{
"id": "50adf64c34fa750bb036121e",
"name": "2013 Ford Shelby GT500\u2122",
"thumb": "/static/images/carthumbs/24824.png",
"user_id": "502a754b34fa75280c000a7e"
}
],
"user": {
"id": "502a754b34fa75280c000a7e",
"car_ids": [
"50ace47234fa7557403e7f02",
"508668cc34fa753b78784ca2",
"50c7545334fa750ab8cb3ac2",
"50adf64c34fa750bb036121e"
],
"player_type": "Standard Player",
"username": "WillMckenzie"
}
}
Everything seems to load fine if I call App.User.find("502a754b34fa75280c000a7e"), but when I try and access the cars property on the user it triggers a second http request to the cars api route. It was my understanding that this shouldn't be necessary, and if I change the ids to basic ints, it doesn't. As I'm using Mongo as my DB my ids have to be in this string format.
Any suggestions as to what I'm doing wrong?
Cheers
Will
Here's the answer so people don't have to dig through the comments:
"I had one car id listed that wasn't in the list of cars returned. They're grabbed slightly differently and I obviously had a bad record in there. This meant it always thought it needed to reload that record so would keep requesting. Obviously when I was faking the integer ids it was masking this." - OiNutter