Using MongoDb version 3.2.7
I have a mongoose schema like this which has an array of stock in branch schema. I want to select a subCategoryId in stock array and get the currentPrice of that subCategoryId only, for that I am using query
var getCriteria = { "stock.subCategoryId": subCategoryId }
var update = { "stock.$.currentPrice": currentPrice }
This query works for me at the time of updating the value as I am able to update the currentPrice of selected subCategoryId perfectly. But when I want to get a price of particular subCategoryId the following query gets me all the stocks in the branch collection. The query I am using is this:
var getCriteria ={ "stock.subCategoryId": subCategoryId }
Mongoose Schema
var branch = new Schema({
branchName: { type: String, trim: true, index: true, default: null },
isBlocked: { type: Boolean, default: false, required: true },
email: { type: String, trim: true, required: true, unique: true, index: true },
password: { type: String, required:true },
accessToken: { type: String, trim: true, index: true, unique: true, sparse: true },
stock: [stock],
});
var stock = new Schema({
categoryId: { type:Schema.ObjectId, ref: "categoies", default: null },
subCategoryId: { type:Schema.ObjectId, ref: "subCategories", default: null },
currentPrice: { type: Number },
isBlocked: { type: Boolean, default: false, required: true },
Date: { type: Date, default: Date.now, required: true }
});
To retrieve only the matching array element try this:
branch.find(getCriteria,{'stock.$' : 1},function(err,branch){...});
stock.$ will help you to retrieve only the matched element from the array.
Related
I want to add an auto-increment field in the MongoDB schema for
Interview.round.count field i.e. whenever I will Update the interview field it will automatically increase the Count value with +1
//Here is My Schema Field
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const { Schema } = mongoose;
const InterviewSchema = new Schema(
{
name: {
type: String,
required: true,
trim: true,
maxlength: 30,
},
email: {
type: String,
required: true,
trim: true,
},
gender: {
type: String,
required: true,
},
contactNumber: {
type: Number,
required: true,
}
interview: [
{
interviewerName: {
type: String,
trim: true,
},
round: {
count: {
type: Number,
default: 0,
},
type: {
type: String,
default: 'telephonic',
},
},
recommendation: {
type: String,
default: '',
},
},
],
},
},
{
timestamps: true,
},
);
InterviewSchema.plugin(mongoosePaginate);
const InterviewProcess = mongoose.model('interviewprocess', InterviewSchema);
module.exports = InterviewProcess;
Interview schema is defined as an array object.
My goal is to auto-increment the Interview.round.count i.e. for the count field
Can anyone please help me?
I have a "cart" model, and within my "order" model, I would like to have an array that receives the information sent by "cart" stored in an array. How can I do this through ref?
const mongoose = require('mongoose');
const CartSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
note: {
type: String,
required: true,
},
price: {
type: Number,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Cart", CartSchema);
order
const mongoose = require('mongoose');
const OrderSchema = new mongoose.Schema(
{
list: {
name: String,
notes: String,
},
totalAmount: {
type: Number,
required: true,
},
payment: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
addressNote: {
type: String,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", OrderSchema);
Here in "list" I would like it to be an array that receives cart model information
Can I do this through ref? What would be the best possible way?
I am using node.js express.js and mongoose to develop my back end, I have this mongoose schema where I want to add a field called NumberRecords for every stored document this field will have the length value of the array csvData, I looked around some similar question here and I found I can use this pre function which I did but I get nothing on my database no field called NumberRecords is being added.
How do I fix this?
const rowSchema = new mongoose.Schema({
SESSION_ID: {
type: String,
required: false,
},
CARD_NUMBER: {
type: String,
required: false,
},
TERMINAL_ID: {
type: String,
required: false,
},
EXTERNAL_STAN: {
type: String,
required: false,
},
})
const csvSchema = new mongoose.Schema(
{
fileName: { type: String, required: true },
csvData: { type: [rowSchema], required: true },
NumberRecords: { type: Number, required: true },
},
{
timestamps: true,
}
);
csvSchema.pre("validate", function (next) {
this.NumberRecords = this.csvData.length;
next();
});
module.exports = mongoose.model("csvRecords", csvSchema);
I just started learning express and mongodb. I recently faced the kind of problem, I'm trying to select all the subdocuments which are inside of Room model.
const books = await Room.find().populate('book');
But it returns whole room document when i want to select only bookings field.
Here's the book schema
const bookSchema = new mongoose.Schema({
startDate: {
type: Date,
required: true,
},
endDate: {
type: Date,
required: true,
},
name: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
});
module.exports = mongoose.model("book", bookSchema)
And here's the room schema
const roomSchema = new mongoose.Schema({
currentlyReserved: {
type: Boolean,
default: false,
},
people: {
type: Number,
required: true,
},
roomNumber: {
type: Number,
required: true,
},
pricePerPerson: {
type: Number,
required: true,
},
reservedUntil: {
type: Date,
default: null,
},
reservedBy: {
type: String,
default: null,
},
bookings: {
type: [{ type: mongoose.Schema.Types.ObjectId, ref: "book" }],
},
});
module.exports = mongoose.model("room", roomSchema);
You can project with with second arg to find().
https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection
const books = await Room.find({}, {bookings: 1}).populate('bookings');
Hi I have a Model Customer and its schema
var customerSchema = new Schema({
name: {type: String, required:true, trim: true, index: true, default: null, sparse: true},
cardInfo: { type: [cardInfoSchema]}
})
var cardInfoSchema = new Schema({
customerId : { type: String, required: true, index: true, unique: true,trim : true, sparse: true},
cards: { type:[cardsSchema], default:[]}
}, {_id: false});
var cardsSchema = new Schema({
cardType : { type: String, required: true, default: null, trim : true },
isActive : { type: String, required: true, trim: true }, //0: not active, 1: active
cardId : { type: String, required: true, trim: true },
createdAt : { type: Date, default: Date.now, required: true }
})
I want to add multiple cards of customer so I am using this
var dataToSet = {
'cardInfo.customerId': '25934285649875',
$push: {
'cardInfo.cards': {
cardId: 'somecardid,
cardType: 'type',
createdAt: new Date().toISOString(),
isActive: true
}
}
};
But I am getting this error.
cannot use the part (cardInfo of cardInfo.customerId) to traverse the element ({cardInfo: []})
Please help me in writing the query to add card of customer using mongodb or mongoose.
Try the positional $ operator in your update which acts as a placeholder for the first element that matches the query document, and when you use it make sure the cards array field must appear as part of the query document. In your case you'd want to add a card document into the 'cards' array, but only if the cardId doesn't exist:
var query = {
"cardInfo.cards.cardId": { "$nin": ["somecardid"] }
};
var update = {
"$push": {
"cardInfo": { "customerId": "25934285649875" },
"cardInfo.$.cards": {
cardId: "somecardid",
cardType: "type",
createdAt: new Date().toISOString(),
isActive: true
}
}
};
Customer.update(query, update, function (err, result) { ... });