I am trying to use alias names for crud operations. It only works well for create query. But for find and findOne I am using translateAliases in hooks. Main issue is for read query, for find and findOne result, the result does not contain alias name, but I need them.
This is my schema:
const someSchema = new mongoose.Schema({
f1: {
type: Number,
default: -1,
alias: 'field1'
},
f2: {
type: Boolean,
default: false,
alias: 'field2'
}
}, {
timestamps: true
});`
If I am saving data with alias names, it is working, but for fetching/querying. I am using hooks:
`someSchema.pre('find', function() {
this.model.translateAliases(this.getQuery());
});
someSchema.pre('findOne', function() {
this.model.translateAliases(this.getQuery());
});
Now what I want is in result from these queries, the data should contain alias name.
Related
I have a project with NestJS, Typescript and Typeorm. I'm working with the following class Entity
class Event {
user: string,
createdAt: Date,
type: string,
data: JSON
}
In one of my methods I'm making a query to get some events, but I want to access just a few properties of the data attribute because the object has a lot information I don't really need. The problem is that when I try to access the json, for example: receivedEvent.data.myProperty typescript tells me that this property is not available in type JSON. The only solution I can think of is changing the type of the data attribute to a string and parse it to json after the query, but I want to know if there is any other solution to this. This is the code I'm using to query the events:
async getLogs(loanId: string): Promise<Event[]> {
const events = await this.eventRepository.find({
select: ['createdAt', 'user', 'type', 'data'],
where: {
type: In([
'early_payoff',
]),
data: Raw(
/* istanbul ignore next */
() => 'data->"$.GUID" = :id',
{ id: loanId },
),
},
order: {
id: 'DESC',
},
});
console.log(events);
return events.map(e=>{
/// This is where my problem is
const json: any = {"withdrawReason": e.data.withdrawReason}
return {...e, data: json}
});
}
I found a quick to solution to this problem. I set the event.data to another variable with type and after that Typescript doesn't throws error.
return events.map(e=>{
/// This is where my problem was
const json: any = e.data
const jsonData: any = {"withdrawReason": json.withdrawReason}
return {...e, data: jsonData}
});
I am trying to return a nested Object that I declared in my mongoose model as follows:
const MessageSchema = new Schema({
messageLog: [
{
transcript: {
type: String
},
recipient: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
sender: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
}]
});
however I am not able to get the value for the inner object back when I try to query for it via a graphql resolver (transcript, sender, recipient are null on gql playground, but updated in db) I have set it up as follows:
query = args.messageId ? { _id: args.messageId } : { _id: new ObjectId() };
const message = await Message.findOneAndUpdate(query, {$addToSet: {messageLog: {transcript: args.messageBody, sender: args.senderId, recipient: args.recipientId}}}, {$setOnInsert: args, upsert: true, new: true, runValidators: true})
return message.messageLog;
I am able to create the new object and the nested messageLog in the db but I can only return the id for some reason as opposed to the the messageLog array of objects. Usually the issue lies in how I am resolving (resolvers) but I am going to put my typeDef here as well in case the issue lies there.
type Message {
_id: ID
transcript: [String]
recipient: [User]
sender: [User]
}
So the solution in case anyone has a similar schema setup and issue is to reference the the typeDefs with the nested levels as well. So since transcript, recipient and sender were nested a level down, the typeDef would have to be defined for the nested object and then referenced on the message type as follows:
type messageLog {
_id: ID
transcript: String
recipient: User
sender: User
}
type Message {
_id: ID
messageLog: [messageLog]
}
and to use populate for the User since it was a schema referenced by the objectId
i want to add that question schema as the type inside that questions array in topicSchema, but cant do that as it gives error. How can i add array of particular schema type. Is there a way?
const question_schema = require('./Question')
const topicSchema = new Schema(
{
name: {
type: String,
required: true,
enum: [...Object.values(topics_enum)]
},
icon: {
type: String,
required: true
},
questions: [question_schema]
},
{
versionKey: false,
}
);
module.exports = mongoose.model("topics", topicSchema);
To my understanding, use type and ref,
you need to use this formatting in order to reference the schema itself:
questions: [{
type: Schema.Types.ObjectId,
ref: 'question_schema'
}
],
The type (Schema.Types.ObjectId) will add the object id for each question in the array (which you can then iterate over later to find each question by those IDs), and the ref ('question_schema') allows mongoose to figure out which of your schemas it should be referencing. As long as the ref is the same as your variable name, it should connect using ref.
You need to state the type of the object as an array, try:
questions:{
type: [question_schema],
}
I'm implementing GraphQL to query data from the web with web driver.
My problem is that I cannot figure out how to use one argument as input for 2 different queries. So basically It is querying data from 2 different sites and has the same input which is usually 4 character Symbol.
What I want my query to look like.
{
Webpage1(symbol:"AABC"){
data_from_site,
some_other_data
Webpage2(symbol:"AABC"){ ##get rid of this Double attribute entry
data_from_page2
}
}
}
How can I pass only one argument be And get data from both sites?
So it will be in the root context for the resolver to use.
I'm fairly new to GraphQL and have tried defining separate GraphQLObjectType in order to solve this problem. But what I'm really looking for is unified data in the same object and arguments parsed from the parent object.
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
Webpage1: {
type: Website1,
args: {
symbol: { type: GraphQLString },
//date: { type: GraphQLString }
},
resolve: function (_, { symbol }) {
return {
symbol
};
}
},
Webpage2: {
type: History,
resolve: function (_, { symbol }) {
return {
symbol
};
}
}
}
})
})
If I'm understanding your question correctly, you can keep your schema as is and just utilize a variable when sending your query:
query MyQuery($mySymbol: String){
Webpage1(symbol:$mySymbol) {
data_from_site
some_other_data
}
Webpage2(symbol:$mySymbol) {
data_from_page2
}
}
Variables are defined at the top of your document, as part of your operation definition. Once defined, they can used any number of times inside the document anywhere you would use the same kind of literal value. You can check out the official tutorial on variables here and the spec here.
I have problem using uuid with new mongoose.Schema. I use it to generate unique key for a device and save it to the MongoDb using Node.js. the problem is that it uses the same UUID every time.
This is the model:
const mongoose = require('mongoose');
const uuid = require('uuid/v4');
const DeviceSchema = new mongoose.Schema({
deviceNumberHash: {
type: String,
required: true
},
receivingKey: {
type: String,
default: uuid()
}...
});
And this is what is saved in MongoDb:
Any idea what's wrong?
You're calling uuid and passing its return value in as the default to use.
Instead, pass in the function (by not putting () after it):
const DeviceSchema = new mongoose.Schema({
deviceNumberHash: {
type: String,
required: true
},
receivingKey: {
type: String,
default: uuid // <========== No ()
}...
});
The default can be a function per the docs (an example there uses default: Date.now to provide a default for a date field, for instance).