I have collection mongodb like this:
var CategorySchema = new mongoose.Schema({
Name: String,
Description: String,
Picture: {
type: String,
default: 'http://placehold.it/64x64'},
Level: {
type: Number,
default: 1},
Owner:{
type: Schema.ObjectId,
ref: 'Category'}
});
How can get result using Owner, because api of this just can get result by _id.
You can do it like this:
var owner = {ref:'Category};
category_model.findOne({owner: owner}, 'ref', {lean: true}, function (err, owner) {
});
Related
I am trying to grab documents based on populated subdocuments.
Here are my models
// User model
var UserSchema = new mongoose.Schema({
username: {type: String, required: true, trim: true},
firstName: {type: String, required: true, lowercase: true},
lastName: {type: String, required: true, lowercase: true},
phone: {type: String, required: false},
email: {type: String, required: true},
password: {type: String, required: true},
blogs: {type: mongoose.Schema.Types.ObjectId, ref: 'Blogs'}
}, {timestamps: true});
// Blog Model
var BlogSchema = new mongoose.Schema({
description: String,
tags: [String],
other: [Object],
}, {timestamps: true});
This is how I am grabbing documents
fetchAllByFilter: async function(req, res) {
try {
let result = await Users.find({}).populate('blog');
return res.status(200).send(result);
} catch (err) {
return res.status(200).send({error: err});
}
},
Now my main question is, how would I grab Users based on their Blogs referenced documents?
For example, Find Users with Blogs that has Blog.tags of "food", "cars", "movies" and/or Blog.other of [{...SomeObject}, {...SomeOtherObject}]
looking at mongo docs match an array, you could make a utility function somewhat like this...
async function findByTag(tag) {
const blogIds = await Blog.find({ tags: tag }).select("_id");
const users = await User.find({
blogs: { $in: blogIds.map((blog) => blog._id) }
}).populate("blog");
}
I'm trying to fetch some documents from my db. In each document, there is a field called 'owner' which is an ObjectId of a user. I want to fetch all of the documents of a specific user. I have the user id and when I'm trying to do something like this:
exports.getBoxes = function(req, res) {
const { user } = res.locals;
const query = db.Box.find();
query.where('owner').equals(user._id);
query.exec(function(err, boxes) {
console.log(boxes);
});
}
I get an empty array. I saw in my db and there are many boxes that corresponds to this query. What's wrong with it?
UPDATE
Here is my schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamps');
const BoxSchema = new Schema({
description: {
type: String,
trim: true
},
producer: {
type: String,
trim: true
},
cycle: {
type: String,
trim: true
},
owner: {
type: Schema.ObjectId,
ref: 'Supplier'
},
event: {
type: Schema.ObjectId,
ref: 'Event'
},
type: {
type: String,
enum: []
},
creditTerms: {
type: String,
enum: ['Cash', '30 Days', '60 Days', '90 Days', '120 Days']
},
bids: [{
type: Schema.ObjectId,
ref: 'Bid'
}],
looking: [{
type: Schema.ObjectId,
ref: 'User'
}],
sold: Boolean,
paid: Boolean,
delivered: Boolean,
sealed: Boolean,
initialPrice: Number,
value: Number,
cts: Number,
ppc: Number,
finalPrice: Number
});
BoxSchema.plugin(timestamps);
module.exports = mongoose.model('Box', BoxSchema);
And here is an example of documents that I try to fetch:
https://i.gyazo.com/38f2d16d6831b831adb3cc448ef74d01.png
Okay guys I managed to solve this problem. The problem was that the owner field in the box schema referenced a Supplier object, not a User object. So I solved it like so:
const { user } = res.locals;
return db.Supplier.findOne({ userId: user._id })
.populate('boxes').exec(function(err, supplier) {
if(err || !supplier) return res.sendStatus(404);
res.json(supplier.boxes);
});
just started learning mongodb, currently i have this schema
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
}});
and i wanted to update it to be like this, but currently its not working right now, when i checked it on the mongo console the schema is still the old one
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
this is the best i've come up with after reading this post, but it throw me an error TypeError: Undefined type undefined at author.required Did you try nesting Schemas? You can only nest using refs or arrays.
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: {
type: String,
required: true,
default: null
}
}
});
You can't use Schema like that instead just make another authorSchema and use it as array.
var mongoose = require('mongoose');
var authorSchema = new mongoose.Schema({
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: {
type: String,
required: true,
}
})
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: [authorSchema]
})
Could you help me please.
I searched the internet and could not find any solutions.
How create query for a child to use the parameters of the parent?
var Photos = new Schema({
photo_id: {type: String, required: true},
photo_path_low: { type: String, required: true }
});
var Users = new Schema({
user_id: { type: String, required: true },
count_coins: { type: Number, default: 20 },
photos_relation: [Photos]
});
...
... some code
...
PhotoModel.findOne().where('parent.count_coins').gt(1)..... // parent for Example
For this case there are Object-references:
var Photos = new Schema({
photo_id: {type: String, required: true},
photo_path_low: { type: String, required: true }
createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
});
Then, when you make your query, you can populate references like this:
Photo.findOne({_id: 123})
.populate('createdBy')
.exec(function(err, post) {
// do stuff with post
});
You can find more in this mongoose documentation.
I have two mongoose schema as following
var ServiceSubType = new Schema({
displaySubTypeName : String,
subTypeDescription : String,
status : { type: String, default: Constants.ACTIVE },
lastUpdatedOn : Date,
createdOn : { type: Date, default: Date.now }
} , { collection: 'SERVICE_SUB_TYPES' });
and
var ServiceType = new Schema({
displayName : String,
description : String,
status : { type: String, default: Constants.ACTIVE },
lastUpdatedOn : Date,
serviceSubTypeId : {type: Schema.Types.ObjectId, ref: 'ServiceSubType', index: true},
createdBy : { type: Schema.Types.ObjectId, ref: 'SystemUser', index: true },
createdOn : { type: Date, default: Date.now }
} , { collection: 'SERVICE_TYPES' });
I have populated Type Object as below
module.exports.addNewServiceType = function(serviceType_obj, callback) {
serviceType_obj.save(serviceType_obj,callback);
}
Now I am trying to populate ServiceSubType document and then at the same time trying to populate "serviceSubTypeId" of ServiceType object referenced to ServiceSubType created.
Here is my piece of code for the same purpose.
module.exports.addServiceSubType = function(serviceTypeObjId, serviceSubType_obj, callback) {
serviceSubType_obj.save(serviceSubType_obj, function (error, serviceSubType) {
});
serviceSchema.ServiceType.findById(serviceTypeObjId, function (err, serviceType) {
var opts = { path: 'serviceSubTypeId'};
serviceSchema.ServiceType.populate(serviceType, opts, function (err, user) {
console.log(serviceType);
});
}).exec(callback);
}
But it is not workign and not populating any value in Existing SubType object.
I admit my approach could be very wrong as I am very new in this technology. Appreciate any kind of help to run this piece of code as expected.
Thanks
Ajoy
I think your ref should be the same setting as the collection on the object
serviceSubTypeId : {
type: Schema.Types.ObjectId,
ref: 'SERVICE_SUB_TYPES', <==== your collection type goes here
index: true
},
Mongoose doesn't know anything about your JavaScript object types. Instead, it tracks things based on the collection name that you provide (or that it generates).
update based on comments below
I have some example code that I wrote a while back, and it looks like I'm letting Mongoose generate the collection name for me. However, I am supplying a name to the mogoose.model() call, when registering my type for a collection.
For example, I have a Post type and a User type. The Post contains an author which is a reference to the User.
It looks like this:
// post
// ----
var PostSchema = new mongoose.Schema({
date: {type: Date, required: true, default: Date.now},
title: {type: String, required: true},
content: {type: String, required: true},
author: {
type: SchemaTypes.ObjectId,
ref: "user"
},
comments: [CommentSchema]
});
var Post = mongoose.model("blog", PostSchema);
// user
// ----
var UserSchema = mongoose.Schema({
firstName: {type: String},
lastName: {type: String},
username: {type: String, required: true, index: {unique: true}},
email: {type: String, required: true},
password: {type: String, required: true},
url: {
type: mongoose.Schema.Types.ObjectId,
ref: "url"
}
});
User = mongoose.model("user", UserSchema);
In this example code, I'm setting the ref to "user" because I am registering my model as "user" down below, in the mongoose.model method call.
Are you registering your models using mongoose.model and supplying a name? if so, use that name.