Mongodb in array query wont get any result - javascript

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},
});

Related

Remove MongoDB documents that are more than 6 months old

I’m using Mongoose to connect with my MongoDb cluster.
My site has a logging feature. I would like these logs to deleted once they are 6 months old. To do this, I have a file that runs every day to delete documents that are more than 6 months old.
However, the deleteMany() function does not provide me with context to run a function on each document, only that every document has a specific value.
Dates are stored as numbers (shown below)
const mongoose = require('mongoose');
let Sch = new mongoose.Schema( {
id: {
type: String,
default: '',
required: true,
},
password: {
type: String,
default: '',
required: true
},
email: {
type: String,
default: '',
required: true
},
first_name: {
type: String,
required: true,
default: 'John'
},
last_name: {
type: String,
required: true,
default: 'Doe'
},
username: {
type: String,
default: '',
required: true
},
seven_shifts: {
type: Object,
default: {},
},
positouch: {
type: Array,
default: {}
},
departments: {
type: Array,
default: [],
required: true
},
locations: {
type: Array,
default: [],
required: true
},
tip_periods: {
type: Array,
default: []
},
w_4: {
type: String,
default: ''
},
employedSince: {
type: Number
},
notes: {
type: Array,
default: []
},
last_login: {
type: Number
},
});
module.exports = new mongoose.model('User', Sch, 'users');
All I need is a way to check if the number in "date" is less than the one I provide in the function
Does anybody know of a way I can delete the matching documents in one query?
Thanks.

How to print Mongoose object properties with console.log?

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?

Get parent data based reference ID on Node.js and MongoDB

I am trying to get products data based on orders products id and below is my Order Model
import mongoose from 'mongoose';
const { ObjectId, String, Number } = mongoose.Schema.Types;
const OrderSchema = new mongoose.Schema({
user: {
type: ObjectId,
ref: "User"
},
products: [
{
quantity: {
type: Number,
default: 1
},
product: {
type: ObjectId,
ref: "Product"
}
}
],
email: {
type: String,
required: true
},
total: {
type: Number,
required: true
},
status: {
type: String,
required: true,
default: 'pending',
enum: ["pending", "delivered"]
}
},{
timestamps: true
});
export default mongoose.models.Order || mongoose.model("Order", OrderSchema);
The Product Model:
import mongoose from 'mongoose';
const { String, Number } = mongoose.Schema.Types;
const ProductSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
productType: {
type: String,
required: true
},
sku: {
type: String,
unique: true
},
description: {
type: String,
required: true
},
mediaUrl: {
type: String,
required: true
}
},{
timestamps: true
});
export default mongoose.models.Product || mongoose.model('Product', ProductSchema);
And the query is like below for all orders:
const orders = await Order.find()
.sort({ createdAt: 'desc' })
.populate({
path: "products.product",
model: "Product"
});
// console.log(orders)
res.status(200).json({ orders });
The concept is when creating an order it's creating with product id and I want to fetch the products based on the order product id.
And this way it showing
MongooseError [MissingSchemaError]: Schema hasn't been registered for model "Product".
How can I solve that?
Thanks
In the Order model you might be import the Product model then in the ref you use without quotation like
ref: Product
That is the way I think.
Thanks

Mongoose not saving all fields

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

Save JSON object to MongoDB inside String field

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

Categories