How to change sub document after finding with mongoose - javascript

I have some code like below using mongoose.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/hoge');
var UserSchema = new Schema({
name: String,
children: [ChildSchema],
});
var ChildSchema = new Schema({
name: String,
}, {_id: false});
var User = mongoose.model('User', UserSchema);
var Child = mongoose.model('Child', ChildSchema);
User.findOne({_id: '52299322fdbbdec515000001'}, function(err, user) {
console.log(user);
for (var i=0; i<user.children.length; i++) {
var child = user.children[i];
child.name = 'newchild';
}
user.save(function(err) {
console.log(user);
mongoose.disconnect();
});
});
And here is my record in mongodb.
{
"name" : "u1",
"_id" : ObjectId("52299322fdbbdec515000001"),
"children" : [ { "name" : "c2" } ],
"__v" : 0
}
When I run the script, it outputs below.
{ name: 'u1',
_id: 52299322fdbbdec515000001,
__v: 0,
children: [ { name: 'c2' } ] }
{ name: 'u1',
_id: 52299322fdbbdec515000001,
__v: 0,
children: [ { name: 'newchild' } ] }
But my record in mongodb has not been changed. Why?
FYI, the record changed if I insert this code before saving.
user.children.push({name: 'somechild'});

Sorry, I've resolved myself.
The problem is the order of declarating Schemas.
It worked if I tried this change.
/* first, children's schema */
var ChildSchema = new Schema({
name: String,
}, {_id: false});
/* seconds, parent's schema */
var UserSchema = new Schema({
name: String,
children: [ChildSchema],
});

Related

how to push new values to existing array in mongoose [duplicate]

Basically I have a mongodb collection called 'people'
whose schema is as follows:
people: {
name: String,
friends: [{firstName: String, lastName: String}]
}
Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends array.
In a secondary place in the application, a form is in place to add friends. The form takes in firstName and lastName and then POSTs with the name field also for reference to the proper people object.
What I'm having a hard time doing is creating a new friend object and then "pushing" it into the friends array.
I know that when I do this via the mongo console I use the update function with $push as my second argument after the lookup criteria, but I can't seem to find the appropriate way to get mongoose to do this.
db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});
Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };
There are two options you have:
Update the model in-memory, and save (plain javascript array.push):
person.friends.push(friend);
person.save(done);
or
PersonModel.update(
{ _id: person._id },
{ $push: { friends: friend } },
done
);
I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).
However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the latter when it's absolutely necessary.
The $push operator appends a specified value to an array.
{ $push: { <field1>: <value1>, ... } }
$push adds the array field with the value as its element.
Above answer fulfils all the requirements, but I got it working by doing the following
var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
People.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { friends: objFriends } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
)
Another way to push items into array using Mongoose is- $addToSet, if you want only unique items to be pushed into array. $push operator simply adds the object to array whether or not the object is already present, while $addToSet does that only if the object is not present in the array so as not to incorporate duplicacy.
PersonModel.update(
{ _id: person._id },
{ $addToSet: { friends: friend } }
);
This will look for the object you are adding to array. If found, does nothing. If not, adds it to the array.
References:
$addToSet
MongooseArray.prototype.addToSet()
Use $push to update document and insert new value inside an array.
find:
db.getCollection('noti').find({})
result for find:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
update:
db.getCollection('noti').findOneAndUpdate(
{ _id: ObjectId("5bc061f05a4c0511a9252e88") },
{ $push: {
graph: {
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
}
})
result for update:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
First I tried this code
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
}
);
But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element !
So the simple solution is written below
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
{ upsert: true }
);
Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements !
The upsert = true option creates the object if it doesn't exist. default is set to false.
if it doesn't work use below snippet
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();
An easy way to do that is to use the following:
var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();
In my case, I did this
const eventId = event.id;
User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();
Push to nested field - use a dot notation
For anyone wondering how to push to a nested field when you have for example this Schema.
const UserModel = new mongoose.schema({
friends: {
bestFriends: [{ firstName: String, lastName: String }],
otherFriends: [{ firstName: String, lastName: String }]
}
});
You just use a dot notation, like this:
const updatedUser = await UserModel.update({_id: args._id}, {
$push: {
"friends.bestFriends": {firstName: "Ima", lastName: "Weiner"}
}
});
This is how you could push an item - official docs
const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);
const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();
// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
$each: [1, 2],
$position: 0
});
doc.nums;
// This is the my solution for this question.
// I want to add new object in worKingHours(array of objects) -->
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
// employeeRoutes.js
const express = require("express");
const router = express.Router();
const EmployeeController = require("../controllers/employeeController");
router
.route("/:id")
.put(EmployeeController.updateWorkingDay)
// employeeModel.js
const mongoose = require("mongoose");
const validator = require("validator");
const employeeSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please enter your name"],
},
address: {
type: String,
required: [true, "Please enter your name"],
},
email: {
type: String,
unique: true,
lowercase: true,
required: [true, "Please enter your name"],
validate: [validator.isEmail, "Please provide a valid email"],
},
phone: {
type: String,
required: [true, "Please enter your name"],
},
joiningDate: {
type: Date,
required: [true, "Please Enter your joining date"],
},
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
const Employee = mongoose.model("Employee", employeeSchema);
module.exports = Employee;
// employeeContoller.js
/////////////////////////// SOLUTION IS BELOW ///////////////////////////////
// This is for adding another day, entry and exit time
exports.updateWorkingDay = async (req, res) => {
const doc = await Employee.findByIdAndUpdate(req.params.id, {
$push: {
workingHours: req.body,
},
});
res.status(200).json({
status: "true",
data: { doc },
});
};
https://www.youtube.com/watch?v=gtUPPO8Re98
I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.
---- Person model
const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema = mongoose.Schema;
const productSchema = new Schema({
friends : [SingleFriend.schema]
});
module.exports = mongoose.model('Person', personSchema);
***Important: SingleFriend.schema -> make sure to use lowercase for schema
--- Child schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SingleFriendSchema = new Schema({
Name: String
});
module.exports = mongoose.model('SingleFriend', SingleFriendSchema);

Why after populate array of values is becoming null?

I want to populate answers(comments) on my post . But on populating it becomes null while before that it stores fine of storing Id's of answer.
My schema of post
var doubtsSchema = new mongoose.Schema({
title : String,
content : String,
tags : String,
created : {
type : Date,
default : Date.now},
author : {
id : {
type : mongoose.Schema.Types.ObjectId,
ref : "User"},
username : String},
answers : [{
type : mongoose.Schema.Types.ObjectId,
ref : "Answers"}]});
module.exports = mongoose.model("Doubts",doubtsSchema);
My schema of answer
var answersSchema = new mongoose.Schema({
content : String,
created : {
type : Date,
default : Date.now},
author : {
id : {
type : mongoose .Schema .Types . ObjectId,
ref : "User"},
username : String},
likes_count : Number});
module.exports = mongoose.model("Answers",answersSchema);
Populate is not working
Doubts.findById(req.params.id).populate('answers').exec(function(err,foundDoubt) {
if(err) {
console.log(err);
} else {
console.log("here");
console.log(foundDoubt);
res.render("doubts/show",{doubt : foundDoubt});
}
});
I made a simple example, it works
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/test", {useNewUrlParser: true});
const UserSchema = new mongoose.Schema({
name: String,
comments: [{type: mongoose.Schema.Types.ObjectId, ref: "Comments"}]
});
const CommentSchema = new mongoose.Schema({
content: ""
});
const Users = mongoose.model("Users", UserSchema);
const Comments = mongoose.model("Comments", CommentSchema);
// Adding data
Promise.all([
new Comments({content: "test 1"}).save(),
new Comments({content: "test 2"}).save(),
new Comments({content: "test 3"}).save()
]).then(result => {
result = result.map(r => r._id);
new Users({name: "test", comments: result}).save().then(user => {
// Getting with populate
Users.findById(user._id).populate("comments").then(console.log);
})
}).catch(console.error);
In console:
{ comments:
[ { _id: 5c979d9dedc0b1db90fe81dd, content: 'test 1', __v: 0 },
{ _id: 5c979d9dedc0b1db90fe81de, content: 'test 2', __v: 0 },
{ _id: 5c979d9dedc0b1db90fe81df, content: 'test 3', __v: 0 } ],
_id: 5c979d9dedc0b1db90fe81e0,
name: 'test',
__v: 0 }
Maybe it will help to find the error

Working with nested arrays in MongoDB and Mongoose [duplicate]

Basically I have a mongodb collection called 'people'
whose schema is as follows:
people: {
name: String,
friends: [{firstName: String, lastName: String}]
}
Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends array.
In a secondary place in the application, a form is in place to add friends. The form takes in firstName and lastName and then POSTs with the name field also for reference to the proper people object.
What I'm having a hard time doing is creating a new friend object and then "pushing" it into the friends array.
I know that when I do this via the mongo console I use the update function with $push as my second argument after the lookup criteria, but I can't seem to find the appropriate way to get mongoose to do this.
db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});
Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };
There are two options you have:
Update the model in-memory, and save (plain javascript array.push):
person.friends.push(friend);
person.save(done);
or
PersonModel.update(
{ _id: person._id },
{ $push: { friends: friend } },
done
);
I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).
However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the latter when it's absolutely necessary.
The $push operator appends a specified value to an array.
{ $push: { <field1>: <value1>, ... } }
$push adds the array field with the value as its element.
Above answer fulfils all the requirements, but I got it working by doing the following
var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
People.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { friends: objFriends } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
)
Another way to push items into array using Mongoose is- $addToSet, if you want only unique items to be pushed into array. $push operator simply adds the object to array whether or not the object is already present, while $addToSet does that only if the object is not present in the array so as not to incorporate duplicacy.
PersonModel.update(
{ _id: person._id },
{ $addToSet: { friends: friend } }
);
This will look for the object you are adding to array. If found, does nothing. If not, adds it to the array.
References:
$addToSet
MongooseArray.prototype.addToSet()
Use $push to update document and insert new value inside an array.
find:
db.getCollection('noti').find({})
result for find:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
update:
db.getCollection('noti').findOneAndUpdate(
{ _id: ObjectId("5bc061f05a4c0511a9252e88") },
{ $push: {
graph: {
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
}
})
result for update:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
First I tried this code
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
}
);
But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element !
So the simple solution is written below
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
{ upsert: true }
);
Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements !
The upsert = true option creates the object if it doesn't exist. default is set to false.
if it doesn't work use below snippet
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();
An easy way to do that is to use the following:
var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();
In my case, I did this
const eventId = event.id;
User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();
Push to nested field - use a dot notation
For anyone wondering how to push to a nested field when you have for example this Schema.
const UserModel = new mongoose.schema({
friends: {
bestFriends: [{ firstName: String, lastName: String }],
otherFriends: [{ firstName: String, lastName: String }]
}
});
You just use a dot notation, like this:
const updatedUser = await UserModel.update({_id: args._id}, {
$push: {
"friends.bestFriends": {firstName: "Ima", lastName: "Weiner"}
}
});
This is how you could push an item - official docs
const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);
const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();
// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
$each: [1, 2],
$position: 0
});
doc.nums;
// This is the my solution for this question.
// I want to add new object in worKingHours(array of objects) -->
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
// employeeRoutes.js
const express = require("express");
const router = express.Router();
const EmployeeController = require("../controllers/employeeController");
router
.route("/:id")
.put(EmployeeController.updateWorkingDay)
// employeeModel.js
const mongoose = require("mongoose");
const validator = require("validator");
const employeeSchema = new mongoose.Schema(
{
name: {
type: String,
required: [true, "Please enter your name"],
},
address: {
type: String,
required: [true, "Please enter your name"],
},
email: {
type: String,
unique: true,
lowercase: true,
required: [true, "Please enter your name"],
validate: [validator.isEmail, "Please provide a valid email"],
},
phone: {
type: String,
required: [true, "Please enter your name"],
},
joiningDate: {
type: Date,
required: [true, "Please Enter your joining date"],
},
workingHours: [
{
workingDate: Date,
entryTime: Date,
exitTime: Date,
},
],
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
const Employee = mongoose.model("Employee", employeeSchema);
module.exports = Employee;
// employeeContoller.js
/////////////////////////// SOLUTION IS BELOW ///////////////////////////////
// This is for adding another day, entry and exit time
exports.updateWorkingDay = async (req, res) => {
const doc = await Employee.findByIdAndUpdate(req.params.id, {
$push: {
workingHours: req.body,
},
});
res.status(200).json({
status: "true",
data: { doc },
});
};
https://www.youtube.com/watch?v=gtUPPO8Re98
I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.
---- Person model
const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema = mongoose.Schema;
const productSchema = new Schema({
friends : [SingleFriend.schema]
});
module.exports = mongoose.model('Person', personSchema);
***Important: SingleFriend.schema -> make sure to use lowercase for schema
--- Child schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SingleFriendSchema = new Schema({
Name: String
});
module.exports = mongoose.model('SingleFriend', SingleFriendSchema);

.populate() not working

I have been working on this for hours and can't find a solution.
I am making a school directory using a
Student Model:
var mongoose = require("mongoose");
var studentSchema = new mongoose.Schema(
{
name: String,
courses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Course"
}
]
});
module.exports = mongoose.model("Student", studentSchema);
and a Course Model...
var mongoose = require("mongoose");
var courseSchema = new mongoose.Schema (
{
name: String,
student: [
{
id:
{
type: mongoose.Schema.Types.ObjectId,
ref: "Student"
},
name: String
}
]
}
);
module.exports = mongoose.model("Course", courseSchema);
When I run .populate on a found student... it does not populate the Course values within the Student...
app.get("/students/:id", function(req, res){
Student.findById(req.params.id).populate("courses").exec(function(err, foundStudent){
if(err){
console.log(err);
} else {
console.log(foundStudent);
res.render("students/show", {student: foundStudent});
}
});
});
The console.log(foundStudent) will display...
{ _id: 597e7a49c945ee13529d0871,
name: 'Collin DeSoto',
__v: 1,
courses: [ { _id: 597e7a4dc945ee13529d0872 } ] }
AFTER the populate.. any ideas?
try this way
User.find(match, function (err, users) {
var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]
var promise = User.populate(users, opts);
promise.then(console.log).end();
})
and prefar this link link

Mongoose populate embedded document in cascade

I am modeling a 'friends' relationship between the user of my micro-blog app. It looks something like this:
in the user.js file
var db = require('mongoose')
, Schema = db.Schema
, ObjectId=Schema.ObjectId;
var userSchema = new Schema({
name:{firstname:String,surname:String},
birthdate:String,
email:String,
posts: [new Schema({
timestamp:Date,
post:{type: ObjectId, ref: 'Post'}
})],
friends: [new Schema({
friend: {type:ObjectId, ref:'User'}
})]
});
module.exports = db.model('User', userSchema);
in the post.js file
var db = require('mongoose')
, Schema = db.Schema,
ObjectId=Schema.ObjectId;
var postSchema = new Schema({
title:String,
content:String,
});
module.exports = db.model('Post', eventSchema);
What I want to achieve is to get all the current user's friends, with their posts array of embedded document, already populated. I clumsily tried with this function:
function getUserFriendsPost(req, res) {
var count = 0;
var output = new Array();
User.findOne({
_id: req.params.id
}, function(err, user) {
for (var i = 0; i < user.friends.length; i++) {
User.findOne({
_id: user.friends[i].friend
}).populate('posts.post').exec(function(err, post) {
output.push(post);
count++;
if (count==user.friends.length) {
res.send(output);
}
});
}
});
}
What I get instead is the friends array correctly returned but the element of the posts having value of null, like this:
[
{
"_id": "4fd5e5f3e45fd10100000004",
"birthdate": "11/11/1911",
"email": "blablabla#gmail.com",
"friends": [],
"posts": [
{
"timestamp": "2012-04-12T16:47:14.576Z",
"post": null,
"_id": "4f870712c488cf0100000081"
},
{
"timestamp": "2012-04-12T16:48:42.282Z",
"post": null,
"_id": "4f87076ac488cf01000000a3"
},
{
"timestamp": "2012-04-12T16:56:26.062Z",
"post": null,
"_id": "4f87093ac488cf0100000117"
}
"name": {
"firstname": "John",
"surname": "Doe"
}
}
]
Is there something that I am overlooking the in populate mechanism or should I proceed with a different approach?
Thank you
With any luck we will get recursive populating in Mongoose 3.0. Until then consider duplicating the data you want from the post (likely only the title) and storing it like this:
var db = require('mongoose')
, Schema = db.Schema
, ObjectId = Schema.ObjectId;
var userSchema = new Schema({
name: {firstname: String, surname: String},
birthdate: String,
email: String,
posts: [new Schema({
timestamp: Date,
title: String,
post: {type: ObjectId, ref: 'Post'}
})],
friends: [new Schema({
friend: {type: ObjectId, ref: 'User'}
})]
});
module.exports = db.model('User', userSchema);
Then you can do a regular:
User.findOne({_id: req.params.id}).populate('friends').exec(function(err, user) { ... })

Categories

Resources