I am trying to save an new document record and some of the fields are being omitted and I have not been able to figure out why.
Here I am setting my order object
var obj = new Order(orderObj);
console.log('orderObj', orderObj);
console.log('obj', obj);
output from console.log:
orderObj { customerId: '5806e2a1759fd9ad7a1f60eb',
products:
[ { productId: '5806e7e3d0073cb4d2946aad',
customerPrice: 100,
notes: 'test',
originalPrice: 99.95,
priceOverride: true } ],
notes: 'some optional order notes',
createdBy: 'test',
total: 99.95 }
obj { customerId: 5806e2a1759fd9ad7a1f60eb,
notes: 'some optional order notes',
createdBy: 'test',
_id: 5808171e802121505e33b252,
shipped: false,
shippedDate: 2016-10-20T01:00:14.019Z,
status: 'Created, Not Shipped',
products:
[ { productId: 5806e7e3d0073cb4d2946aad,
_id: 5808171e802121505e33b253,
quantity: 1 } ] }
Here is my schema:
var orderSchema = new mongoose.Schema({
customerId: { type: mongoose.Schema.Types.ObjectId, ref: 'Customer'},
products: [{
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product'},
quantity: { type: Number, default: 1 },
originalPrice: { Type: Number },
customerPrice: { Type: Number },
priceOverride: { Type: Boolean, default: false },
notes: { Type: String }
}],
notes: String,
status: { type: String, default: "Created, Not Shipped" },
orderDate: { type: Date },
shippedDate: { type: Date, default: Date.now },
shipped: { type: Boolean, default: false },
total: {Type: Number, default: 0.00 },
createdBy: { type: String }
}, schemaOptions);
I cannot figure out why total and product fields (originalPrice, priceOverride) are being dropped from the mongoose Schema instance object.
Of course I figured it out right after I posted this question. The type in the Schema was listed as Type instead of type.
[this answer is for the record]
I had same kind of problem and in a schema where maxconnections and roomNo were not being saved,
I had schema
maxconnections: {type: Number | String },
roomNo: {type: Number | String },
changed it to
maxconnections: {type: Number },
roomNo: {type: String},
and now it works fine (!._.)
Also, when sending a request using postman, use content-type as JSON
Otherwise, data in fields will not get stored
Related
These are the schema from mongoose subdocuments example.
let classTypeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
abilities: {
type: Array,
default: []
},
skills: {
type: Array,
default: []
}
});
let heroSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
minlength: 3,
maxlength: 24
},
classType: [classTypeSchema],
level: {
type: Number,
default: 1
},
currency: {
type: Number,
default: 0
}
});
I tried this way
Hero = mongoose.model('Hero',heroSchema);
console.log(typeof Hero);
console.log(JSON.stringify(Hero, null, 4));
Output
function
undefined
Console.dir gives very detailed output.I am interested only in schemas part
subpaths: {
'classType.name': [SchemaString],
'classType.abilities': [SchemaArray],
'classType.skills': [SchemaArray],
'classType._id': [ObjectId],
'classType.abilities.$': [Mixed],
'classType.skills.$': [Mixed]
},
Is there any other way to print Mongoose properties and methods?
I have 2 collection in same db. I need to using find() to select only "Events" that have "team" equal "team1"
Thank you very much.
I have try to find by population field but it doesn't work.
This is my Event schema
const Event = mongoose.model('Event', new mongoose.Schema({
title: {
type: String,
required: true,
min: 3
},
eventType: {
type: String,
lowercase: true
},
date: {
type: Date,
default: Date.now()
},
venue: String,
country: String,
callLog: {
type: String,
max: 1000
},
eventImgUrl: [String],
editedBy : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
timestamp: {
type: String,
default: Date.now()
}
}));
This is my User schema
const User = mongoose.model('User', new mongoose.Schema({
username: {
type: String,
required: true,
min: 3,
lowercase: true
},
name: String,
email: String,
team: String,
role: {
type: String,
enum: ['admin', 'creator', 'viewer']
}
}));
This is my Controller
const events = await Event.find()
.populate({ path: 'editedBy', select: ['name', 'team']});
res.send(events);
To find all Events that have a team of "team1":
const team1Events = await Event.find({ team: "team1" });
select just specifies the fields returned. You need to use populate match:
await Event.find()
.populate({ path: 'editedBy', match: { yourField: 'yourmatch' }});
I have problem with this error when I am creating a new event with category which exists in my database, for example I created an event with category "javascript" and save it to db, and then i tried to create a new event with categories "javascript, html, css" and then i got this error duplicate key error collection
So my schema for event is this:
const EventSchema = new Schema({
title: {
type: String,
required: true,
min: 3,
max: 100
},
featuredImage: {
type: Object,
},
from: {
type: Date,
required: true
},
to: {
type: Date,
required: true
},
location: {
name: {
type: String
},
address: {
type: Object
}
},
description: {
type: String
},
categories: {
type: Array,
trim: true
},
featured: {
type: Boolean
},
created_by: {
type: Schema.Types.ObjectId,
ref: 'User'
},
slug: {
type: String,
default: null
},
registration: {
type: Boolean
},
tickets: [],
allday: {
type: Boolean
},
speakers: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
attendees: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
comments: [CommentSchema]
}, {
timestamps: true,
usePushEach: true
});
So basically sending array of strings and i got this error.
You probably have some index defined on categories with the unique flag.
You can list the existing indexes with db.events.getIndexes().
You could drop and recreate the culprit (be careful):
> db.events.dropIndex({categories:1})
> db.events.ensureIndex({categories:1},{sparse:true})
Okay, so im getting all convensations with the following query:
return convensations.findOne({}).lean().then(function (convensations) {
console.log(convensations);
});
that would results in the following:
{ _id: 598dd4458b08b727dc53d4a6,
initiateduser: 'spillinfo',
gang: false,
global: false,
members: [ 'spillinfo', '59312d2b329b7535b07e273c' ],
name: 'no name',
__v: 0 }
thats totally fine, but when i do
var userid = "59312d2b329b7535b07e273c";
return convensations.find({members: userid}).lean().then(function (convensations) {
console.log(convensations);
});
it wont get me any results, why is that?
what im i doing wrong to check if the userid is within the members array?
UPDATE EDIT:
DB schema:
new Schema({
initiateduser : String,
name: {type:String, default: 'no name'},
members: { type: Array, default: []},
time: Number,
global: { type: Boolean, default: false},
gang: { type: Boolean, default: false},
});
and example of inserting / creating new:
var conv = new convensations();
conv.members = [userid, user2];
conv.initiateduser = userid;
conv.save(function (err,room) {
edit2:
some debug from query:
getting convensations with userid 59312d2b329b7535b07e273c
Mongoose: convensations.find({ members: ObjectId("59312d2b329b7535b07e273c") }, { fields: {} })
convensations: 0
Change your schema as,
new Schema({
initiateduser : String,
name: {type:String, default: 'no name'},
members: { type: [String], default: []},
time: Number,
global: { type: Boolean, default: false},
gang: { type: Boolean, default: false},
});
I'm working with Mongodb(mongoose) and node.js (express.js).
The model of DB is:
var messageSchema = new Schema({
_channel: { type: Schema.ObjectId, ref: 'Channel', required: true },
_user : { type: Schema.ObjectId, ref: 'User', required: true },
datetime: { type: Date, required: true },
messageType: { type: String, required: true },
publish: { type: Boolean, default: false },
content: {
title: String,
text: String,
}
});
I want save JSON object inside text field (string).
The JSON object is this:
{ event: 'push',
repository: { id: 53012902, name: 'RestAPI' },
ref: 'refs/heads/master',
commits:
[ { id: 'a10202e5b5157ae5ccd2d77d7d578046693ae404',
url: 'https://github.com/1izpena/RestAPI/commit/a10202e5b5157ae5ccd2d77d7d578046693ae404',
author: '1izpena' } ],
sender: { login: '1izpena', html_url: 'https://github.com/1izpena' } }
I convert this in String, but the result is:
{"event":"push","repository":{"id":53012902,"name":"RestAPI"},"ref":"refs/heads/master","commits":[{"id":"a10202e5b5157ae5ccd2d77d7d578046693ae404","url":"https://github.com/1izpena/RestAPI/commit/a10202e5b5157ae5ccd2d77d7d578046693ae404","author":"1izpena"}],"sender":{"login":"1izpena","html_url":"https://github.com/1izpena"}}
And this result is not a String, I need to keep the same format to parse it later as json object.
Any idea?
Many thanks