Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

populate example in mongoose

const Live = new Schema(
  {
    user_id:{ 		// this one populate
            type: Schema.Types.ObjectId,      
            ref: 'User',    //  User Schema
            required: true                 
        },
        title: {
            type: String,
        },
        category:{        // this one populate
            type: Schema.Types.ObjectId,
            ref: 'Category'  // Category Schema
        },
  }
)
let vid = await Live.find({})
            .populate({path:'user_id',select:'name image -_id'})
            .populate({path:'category',select:'category -_id',model:Category})

Comment

what does populate in mongoose mean?

"Mongoose populate() lets you reference documents in other collections.
Population is the process of automatically replacing the specified 
paths in the document with document(s) from other collection(s)."

Source: https://mongoosejs.com/docs/populate.html
Comment

mongoose (populate)

// The 2nd `populate()` call below overwrites the first because they
// both populate 'fans'.
Story.
  find().
  populate({ path: 'fans', select: 'name' }).
  populate({ path: 'fans', select: 'email' });
// The above is equivalent to:
Story.find().populate({ path: 'fans', select: 'email' });
Comment

Mongoose populate example

const members = await subtable.find({ party: req.body.party }).populate({
    path: "user_id", //subtable field which refers to your main table
    select: "fname lname",
  });
Comment

mongoose + populate

app.get('/movies', passport.authenticate('jwt', { session: false }), (req, res) => {
	Movies.find()
		.populate('Genre')
		.populate('Actor')
		.populate('Director')
		.then((movies) => {
			res.status(201).json(movies);
		})
		.catch((err) => {
			console.error(err);
			res.status(500).send(`Error: ${err}`);
		});
});
Comment

mongoose populate()

// populates a single object
User.findById(id, function (err, user) {
  const opts = [
    { path: 'company', match: { x: 1 }, select: 'name' },
    { path: 'notes', options: { limit: 10 }, model: 'override' }
  ];

  User.populate(user, opts, function (err, user) {
    console.log(user);
  });
});

// populates an array of objects
User.find(match, function (err, users) {
  const opts = [{ path: 'company', match: { x: 1 }, select: 'name' }];

  const promise = User.populate(users, opts);
  promise.then(console.log).end();
})

// imagine a Weapon model exists with two saved documents:
//   { _id: 389, name: 'whip' }
//   { _id: 8921, name: 'boomerang' }
// and this schema:
// new Schema({
//   name: String,
//   weapon: { type: ObjectId, ref: 'Weapon' }
// });

const user = { name: 'Indiana Jones', weapon: 389 };
Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
  console.log(user.weapon.name); // whip
})

// populate many plain objects
const users = [{ name: 'Indiana Jones', weapon: 389 }]
users.push({ name: 'Batman', weapon: 8921 })
Weapon.populate(users, { path: 'weapon' }, function (err, users) {
  users.forEach(function (user) {
    console.log('%s uses a %s', users.name, user.weapon.name)
    // Indiana Jones uses a whip
    // Batman uses a boomerang
  });
});
// Note that we didn't need to specify the Weapon model because
// it is in the schema's ref
Comment

populate in mongoose

const mongoose = require('mongoose');
const { Schema } = mongoose;

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
Comment

how to use mongoose populate

{  _id: 59ab1c92ea84486fb4ba9f28,  username: JD,  posts: [    "59ab1b43ea84486fb4ba9ef0",    "59ab1b43ea84486fb4ba9ef1"  ]}
Comment

PREVIOUS NEXT
Code Example
Javascript :: get date in format 
Javascript :: query selector 
Javascript :: spring boot map json to object in controller 
Javascript :: what is ... in javascript 
Javascript :: import bootstrap 4 in react 
Javascript :: ajax post csrf codeigniter 
Javascript :: socket ERR_CONNECTION_REFUSED 
Javascript :: select div with clas 
Javascript :: get response from window.open 
Javascript :: Assume that x is a char variable has been declared and already given a value. Write an expression whose value is true if and only if x is a upper-case letter. 
Javascript :: how to set dropdown value in textbox using jquery 
Javascript :: .html jquery in javascript 
Javascript :: decapitalize javascript string 
Javascript :: node js create or check directory 
Javascript :: nodejs mysql error handling with user example 
Javascript :: how to send dm to every member in discord with discord.js 
Javascript :: ~~ in javascript 
Javascript :: what is angularjs 
Javascript :: rating calculator formula javascript 
Javascript :: buscar una frase e un string js 
Javascript :: dates in javascript 
Javascript :: useEffect() Execute Function When React Component Loads 
Javascript :: random number generator 
Javascript :: set VS Code SSH Remote shell to zsh 
Javascript :: add material angular 
Javascript :: replit node version 
Javascript :: bind this react 
Javascript :: news api react native 
Javascript :: angular playground online 
Javascript :: what is state in react 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =