I have two model and I want to find the last status of each id in customer model from the status model, I'm using aggregate here, but when I console log things it shows, empty, can anyone help please .............................................
/// customer model
///table name is crmcustomers in database
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schemaOptions = {
timestamps: true,
toJSON: {
virtuals: true
}
};
var CrmCustomerSchema = new Schema({
name: String,
shop_name: String,
address: String,
phone: { type: String, unique: true},
comment: String,
email: String,
website : String,
interest: String,
reference : String,
}, schemaOptions);
var CrmCustomer = mongoose.model('CrmCustomer', CrmCustomerSchema);
module.exports = CrmCustomer;
/// status model
///table name is crmcustomerstatuses in database
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schemaOptions = {
timestamps: true,
toJSON: {
virtuals: true
}
};
var CrmCustomerStatusSchema = new Schema({
crm_id : String,
name: String,
shop_name : String,
status : String
}, schemaOptions);
var CrmCustomerStatus = mongoose.model('CrmCustomerStatus', CrmCustomerStatusSchema);
module.exports = CrmCustomerStatus;
////query
CrmCustomer.aggregate([
{
"$lookup": {
"from": "crmcustomerstatus",
"localField": "_id",
"foreignField": "crm_id",
"as": "result"
}
},
]).exec(function(err, results){
console.log(results);
})
///result
[ { _id: 5a1cf755b5268904a476c7d2,
updatedAt: 2017-11-28T05:42:45.239Z,
createdAt: 2017-11-28T05:42:45.239Z,
name: 'istiaque ahmad',
shop_name: 'les mecaron',
address: 'mirpur',
phone: '01764199657',
email: 'nahid#bond.com',
website: 'xccxxxxx',
comment: 'dsfsdf',
interest: 'dsfsdf',
reference: 'dsfsdfsdf',
__v: 0,
result: [] } ]
Reason for getting empty result is _id in CrmCustomer schema is of type of ObjectId, whereas crm_id in CrmCustomerStatus schema is of type String
Modified CrmCustomerStatus Schema
var CrmCustomerStatusSchema = new Schema({
crm_id : ObjectId,
name: String,
shop_name : String,
status : String
Related
I have a simple Mongo DB with two models: Campaign and Donation, where a Campaign is related to many Donations.
Using mongoose I can query for a specific Campaign using an aggregation with a lookup() and it returns all of the related Donations. But if I try to use a populate() statement, no Donations are returned. I cannot figure out why.
Campaign
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
require('models/Donation');
const CampaignSchema = new Schema({
name: {
type: String,
required: true
},
goal: {
type: Number,
required: true
},
donations: [{
type: Schema.Types.ObjectId,
ref: "Donation"
}]
},
{
collection: 'campaigns'
});
mongoose.model('Campaign', CampaignSchema);
Donation
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
require('models/Campaign');
const DonationSchema = new Schema({
campaign: {
type: Schema.Types.ObjectId,
ref: "Campaign",
required: true
},
amount: {
type: Number,
required: true
},
date: {
type: Date,
required: true,
default: Date.now
}
},
{
collection: 'donations'
});
mongoose.model('Donation', DonationSchema);
This code will return a single Campaign based on _id and all of the associated donations:
const filter = {_id: mongoose.Types.ObjectId(req.params.id)};
Campaign.aggregate().match(filter).lookup({
from: "donations",
localField: "_id",
foreignField: "campaign",
as: "donations"}).then((results) => {
console.log(results[0].donations); // HAS ALL OF THE RELATED RECORDS
});
This code returns an empty array for donations:
const filter = {_id: mongoose.Types.ObjectId(req.params.id)};
const campaign = await Campaign.findOne(filter).populate('donations').then((c) =>{
console.log(c.donations); // EMPTY
});
I'm want to join collection mongoDB but I've 2 model in project.
ADMINDETAIL and ADMINDETAIL get UID from member.model.js .
How I populate that.
queue.model.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var queueSchema = Schema(
{
QUEUE: String,
UID: String,
DATETIME: String,
ADMIN_ID: String,
USERDETAIL:{
type: Schema.Types.String,
ref:"MEMBER"
},
ADMINDETAIL:{
type: Schema.Types.String,
ref:"MEMBER"
},
},
{
collection: "QUEUE"
}
);
var QUEUE = mongoose.model("QUEUE", queueSchema);
module.exports = QUEUE;
member.model.js
var mongoose = require("mongoose");
var memberSchema = mongoose.Schema(
{
UID: {type: String},
NAME: {type: String},
SURNAME: {type: String},
IDNUMBER: {type: String},
PHONE: {type: String},
ADDRESS: {type: String},
},
{
collection: "MEMBER"
}
);
var MEMBER = mongoose.model("MEMBER", memberSchema);
module.exports = MEMBER;
queue.router.js
// GET QUEUE BY USER
router.get("/byuid/:UID", (req, res) => {
var {UID} = req.params;
Queue.find({UID})
.populate({Path:"USERDETAIL",model:"MEMBER"})
.populate({Path:"ADMINDETAIL",model:"MEMBER"})
.exec((err, data) => {
if (err) return res.status(400).send(err);
return res.status(200).send(data);
});
});
Error I got.
TypeError: utils.populate: invalid path. Expected string. Got typeof `object`
change the type of filed from String to ObjectId like this:
USERDETAIL:{
type: Schema.Types.ObjectId ,
ref:"MEMBER"
},
ADMINDETAIL:{
type: Schema.Types.ObjectId ,
ref:"MEMBER"
},
},
add your new data after that you can like this for population:
.populate("USERDETAIL ADMINDETAIL")
or
.populate([{
path: 'USERDETAIL ',
model: 'MEMBER'
}, {
path: 'ADMINDETAIL',
model: 'MEMBER'
}])
I think you are missing []
I want to get all the posts with their author details from user model. I am using mongoDB lookup. But getting an empty array. I am matching author.uid from post to _id of user.
I want to get all the posts with their author details from user model. I am using mongoDB lookup. But getting an empty array. I am matching author.uid from post to _id of user.
//Post Model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const postSchema = new Schema({
category : {
type: String
},
content: {
type: String
},
caption: {
type: String
},
tags: [{
type: String
}],
createdAt: {
type: Number,
required: true
},
author: {
uid:{
type: String,
required: true
},
name:{
type: String
}
},
likes:[{
type:String
}],
comments:[{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}]
});
module.exports = mongoose.model('Post', postSchema);
//User Model
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
_id: {
type: String,
required: true
},
name:{
type: String,
required: true
},
avatar:{
type:String
},
bio:{
type: String
},
followers:[
{
type: String
}
],
followings:[
{
type: String
}
],
posts:[{
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
}]
});
module.exports = mongoose.model('User', userSchema);
//Node js
const express = require('express');
const router = express.Router();
const Post = require('../../models/Post');
const User = require('../../models/user');
router.get('/', (req, res) => {
Post.aggregate([
{
$lookup:
{
from: 'User',
localField: "author.uid",
foreignField: "_id",
as: "creator"
}
}
]).exec((err, result) => {
if (err) {
console.log("error" ,err)
}
if (result) {
console.log(JSON.stringify(result));
}
});
});
//Output
{"_id":"5b9c7f30d",
"author": {"uid":"y08RxtsHe","name":"Sujoy Saha"},
"tags": ["#lo"],
"likes":[], "comments[],
"category":"image","content":"jsdnvs","caption":"standing
\n#lol","createdAt":1536982759517,"__v":0,"creator":[]}
You can see, i am getting empty creator array. Please help me out.
mongoose.js pluralizes (adds 's' after your model name) when it creates a collection in MongoDb.
Can you try with from: 'users' in your $lookup clause?
I am learning Mongoose, and got struct on pushing data into array blogs.
my schema is
module.exports = function(mongoose) {
var UserSchema = new Schema({
count:String,
_id : {id:false},
blogs: [{ type: Schema.Types.ObjectId, ref: 'Blog' }]
},
{
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
});
var BlogSchema = new Schema({
blogs:[{
post : String,
title: String,
author : String,
userId: {
type: String,
default: function() {
return crypto.randomBytes(12).toString('hex');
}
},
_id: {type: String, required: true}
}],
});
var models = {
User : mongoose.model('User', UserSchema),
Blog : mongoose.model('Blog', BlogSchema)
};
return models;
}
Problem is here userSchema will always have/be a single object, whcih will keep track of count of total blogs.
I know it can be done using findOneAndUpdate but I don't have id/object created for UserSchema.
Any help is appreciated. Thanks
I need a nested subschema having ids so i tried the below code but data cant inserted
code
My model..
var connection= handler.getConnection();
console.log(connection);
autoIncrement.initialize(connection);
var subSchema = mongoose.Schema({
course_Submodule: [{
type: String,
required: true,
}]
},{ _id : false });
subSchema.plugin(autoIncrement.plugin, {
model: 'Submodule',
field: 'Id_submodule',
startAt: 1,
incrementBy: 1
});
var courseSchema = new Schema({
course_Name: String,
course_Code: String,
course_Submodule: [subSchema],
course_Author: String,
id_subject: String,
id_user: String,
});
courseSchema.plugin(autoIncrement.plugin, {
model: 'Course',
field: 'Id_course',
startAt: 1,
incrementBy: 1
});
var Course = connection.model('Course', courseSchema);
var Submodule = connection.model('Submodule', subSchema);
module.exports = Course;
bt in db data is inserted like this
"_id" : ObjectId("578efe6da667fff80d09d5ed"),
"Id_course" : 214,
"course_Name" : "chemistry1",
"course_Code" : "ch1",
"course_Author" : "David",
"id_subject" : "3",
"course_Submodule" : [
{
"Id_submodule" : 14,
"course_Submodule" : [ ]
},
{
"Id_submodule" : 15,
"course_Submodule" : [ ]
}
],
"__v" : 0
trying these code i cant insert the value of course_Submodule.Is ther any anotherway for this .help me please
Instead of duplicating the data, you can simply store the object id of the other object into your schema.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//Schema for doctors
var StudentSchema = new Schema({
name:{
type: String,
required: true
},
email: {
type: String,
unique: true
},
user : {
type : Schema.ObjectId,
ref: 'User', //i have a different model User
required : true
}
});
module.exports = mongoose.model('Student', StudentSchema);
Your query over student schema can look like this
db.collection.find(//condition, function(err, data){
//your functionality
})
.populate('User', 'dob')
.exec();
My user schema has a field dob.
This is a small and tidy example to avoid duplicacy of data.
Hope it will help.