populate with mongoose pagination - node.js

i tried to fetch data using npm mongoose-paginate but populate is not working
here is my UsersSchema.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var usersSchema = new Schema({
name : String,
created_at : { type : Date, default : Date.now }
});
module.exports = mongoose.model('users',usersSchema);
here is post schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');
var postsSchema = new Schema({
user : { type: Schema.Types.ObjectId, ref: 'users' },
post : String,
created_at : { type : Date, default : Date.now }
});
postsSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('posts',postsSchema);
here is my query
var options = {
sort: { created_at: -1 },
lean: true,
offset: offset,
populate : 'users',
limit: 10
};
postsSchema.paginate({user:user},options,function(err,posts){
if(err){
console.log(err)
return false;
}
console.log(posts)
});
user provide objectID not a users data.
i.e
[{
user : objectID(987654ff11aa),
post : 'post'
}]

If you want to use mongoose-paginate, You can do the following
var query = {};
var options = {
sort: { date: -1 },
populate: 'users',
lean: true,
offset: offset,
limit: 10
};
Post.paginate({}, options, (err, result) => {
//....
})

A populate have following things
Post.find({})
.populate([
// here array is for our memory.
// because may need to populate multiple things
{
path: 'user',
select: 'name',
model:'User',
options: {
sort:{ },
skip: 5,
limit : 10
},
match:{
// filter result in case of multiple result in populate
// may not useful in this case
}
}
])
.exec((err, results)=>{
console.log(err, results)
})

Related

Ref in mongoose model not giving output

I am using mongoose for defining schema. I have two schemas user and Userdetail. i want data from user in userdetail
I have below schema but i am not getting the output. i think the code is correct but not getting why there is no output...instead i am getting empty array.
const mongoose = require("mongoose")
const UserDetailSchema = mongoose.Schema({
Phone : {
type : Number
},
FirstName : {
type : String
},
LastName : {
type : String
},
productimage : {
data : Buffer,
contentType : String
},
IsDeleted:{
type:Boolean,
default:false
},
UserID : {
type : String,
},
data : [{
type: mongoose.Schema.Types.ObjectId,
ref: "user"
}],
},
{timestamps: true})
const UserDetail = new mongoose.model("userdetail",UserDetailSchema);
module.exports = UserDetail;
my user schema is,
const mongoose = require("mongoose");
const UserSchema = mongoose.Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
IsDeleted:{
type:Boolean
},
},
{timestamps: true});
module.exports = mongoose.model("user", UserSchema);
query is,
<pre>
router.get("/UserDetail",async (req,res)=>{
try{
const UsersData= await UserDetail.find();
res.json(UsersData)
}catch(e){
res.status(500).json({ message: e.message })
}
})
</pre>
Even though i am using only find, i must get the data with only id right?
Output is -
Any help would be appreciated
router.patch("/UserDetail/:id",Auth,upload.single("productimage"),async(req,res)=>{
try{
const id = req.params.id;
const updatedData = req.body;
updatedData.productimage = {data: fs.readFileSync('upload/' + req.file.filename),
contentType: 'image/png'};
const options = { new: true };
const result = await UserDetail.findOneAndUpdate(
id, updatedData, options
)
res.send(result)
}catch(e){
res.status(500).json({ message: e.message })
}
})
You can populate a field with the populate function:
const userDetails = await UserDetail.find({}).populate('data').exec();
firstly you need a little change in userID in schema of userDetail.Please make it to UserID:{type : mongoose.Schema.Types.ObjectId}, as it will help you in future during aggregation and you can also remove data from your userDetail model as it will not store any data until you save it.And lastly try to run this aggregation query.
const UsersData= await UserDetails.aggregate([
{$lookup:
{
from: "users",
localField: "userID",
foreignField: "_id",
as: "data"
}
}])
In this way your respective details of users will be displayed in array of data.
Make changes in your model and then populate the data.
const mongoose = require("mongoose")
const UserDetailSchema = mongoose.Schema({
Phone : {
type : Number
},
FirstName : {
type : String
},
LastName : {
type : String
},
productimage : {
data : Buffer,
contentType : String
},
IsDeleted:{
type:Boolean,
default:false
},
UserID : {
type : String,
},
data : {
type: mongoose.Schema.Types.ObjectId,
ref: "user"
},
},
{timestamps: true})
}
populate query
let Model=//import your model here
let userdata=await Model.find().populate("data")
console.log(userdata)

How to delete an object from an array in a mongoose Schema?

User Schema
const UserSchema = new mongoose.Schema({
name : {
type: String,
required : true
},
email : {
type: String,
required : true
},
password : {
type: String,
required : true
},
date : {
type: Date,
default : Date.now,
},
todo : [{ type : mongoose.Schema.Types.Mixed,ref : 'Todo'}]
})
const User = mongoose.model('User',UserSchema);
module.exports = User;
Todo Schema
const TodoSchema = ({
task : String
})
const Todo = mongoose.model('Todo', TodoSchema)
module.exports = Todo;
Database
How do I delete a single todo object i.e("Task 1") from the user?
router.get('/delete/:id',ensureAuthenticated, (req,res)=>{
id = req.params.id
user = req.user
User.update({ }, { "$pull": { task: id }});
tasks = user.todo
res.render("todo/all",{
todo:tasks,
});
})
I have tried all the stackoverflow threads for over 4 hours and I still coudn't figure out what's wrong. Really apprecitate it if you could help it out.
Thank You :)

How to set default value in schema mongoose?

Here I have mongoose schema
const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
items: {
type: [{
id_item: String,
cnt: Number
}],
default: [],
required: true
},
dateExpires: Date
})
cartSchema.pre('save', async function(next) {
this.dateExpires = Date.now() + 7 * 24 * 60 * 60 * 1000;
})
const modelCart = mongoose.model('Cart', cartSchema);
module.exports = modelCart;
I'm calling this function below in one of the routes to create a model, if I send empty value it should return empty array and date in database, but what it returns me is undefined, default value does not trigger. I'm new in Node.js what could be an issue ?
exports.createCart = catchAsync(async (req, res, next) => {
let newCart = await cartModel.create();
console.log(newCart); //undefined, wanted items: [], date: ...
res.status(200).json({
status: "success",
data: {
cart: newCart
}
})
})
Are you sure that you are defining that schema corectly?
Type is a special property in Mongoose schemas.
I think that it should look more like this.
const cartSchema = new mongoose.Schema({
items: {
type: Array,
nested: {
id_item: { type: String },
cnt: { type: Number }
}
default: [],
required: true
},
dateExpires: Date
})

Node JS : Populate auto increment field (Mongoose)

I have two collections, the first is with an auto increment field,
I make a reference in the second collection to the auto increment field, but the find with populate function doesn't return the populated result.
Table1
const mongoose = require("mongoose");
var autoIncrement = require("mongoose-auto-increment");
const table1Schema = mongoose.Schema({
name: String,
displayed: { type: Boolean, default: true },
updatedAt: Date,
createdAt: Date
});
autoIncrement.initialize(mongoose.connection);
table1Schema.plugin(autoIncrement.plugin, { model: "table1", startAt: 1 });
module.exports = mongoose.model("table1", table1Schema);
table2
const table2Schema = mongoose.Schema({
categoryId: { type: Number, ref: "table1" },
displayed: { type: Boolean, default: true }
});
module.exports = mongoose.model("table2", table2Schema);
Query:
var table2_schema = require("../schemas/table2_schema.js");
module.exports.findPopulateFunction = function() {
table2_schema
.find({})
.populate("categoryId")
.exec(function(err, doc) {
console.log("err : ", err);
console.log("docxx : ", doc);
});
};
The problem is that i am using a script to insert the "_id" field number,
I deleted the declaration of the autoincrement and it works successfully

Adding field with migration on mongoDB

So I tried to migrate a new field to the mongoDB collections.
New field is a array that is filled with objects.
The migration runs and is successful, it even shows the new field when
looking the collections.
Problem comes when I try to add data to this field - it shows that the
field is undefined.
What should be done to overcome this problem?
Migration code:
exports.up = async function(db) {
await db
.collection('useractions')
.update({}, {
$set: {
history: []
}
}, {multi: true, upsert: false});
};
Code to populate the new field:
const bookId = req.body.bookId;
const timestamp = req.body.timestamp;
const userId = req.body.userId;
const container = {bookId, timestamp};
UserAction.update(
{ userId },
{$set: { history: container}},
(err, cb) => {
if(err)next({error: err});
res.status(200).json({
cb
})
})
EDIT:
Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userActionModel = new Schema({
userId: {
type: String
},
likes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Podcast',
default: []
}],
tags: {
type: [String],
default: []
},
orderedBook: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Show',
default: []
}]
})
module.exports = mongoose.model('userAction', userActionModel);

Resources