nightMist
nightMist

Reputation: 23

How to declare schematype/datatype of a field in mongoose which is the objetid of an item in another collection?

I am a bit confused by something in MongoDB, when using Mongoose, since I am new to it. I have two collections: authors and posts.

each author in the authors collection have the mongodb inbuilt id associated with them, which as per my understanding is of the schematype/datatype Objectid.

Now in my posts collection, I have a field which has is called author, which should have the value of the author's Objectid, similar to the foreign key concept in SQL.

My question is, which schematype/datatype should I declare the author field in the posts collection? Should I put it as Objectid? If so, would it not auto-increment and not be settable?

Mockup Of Schemas:

var authors = new mongoose.Schema({
name: String,
email: String
});

var posts = new mongoose.Schema({
title: String,
author: **??**
});

Any help would be hugely appreciated!

Upvotes: 0

Views: 358

Answers (1)

robertklep
robertklep

Reputation: 203304

You can use population for that:

var authors = new mongoose.Schema({
  name: String,
  email: String
});

var posts = new mongoose.Schema({
  title: String,
  author: { type: Schema.Types.ObjectId, ref: 'Author' }
  // assuming the model will be called 'Author'
});

To use:

// Get 'author' some how (create a new one, query the
// database for existing authors, etc);
...

// Create a new post and associate it with 'author' by referencing its `_id`:
var post = new Post({
  ...
  author : author._id
});
post.save(...);

The documentation linked above also shows how you can get Mongoose to automatically retrieve the author document when you're querying posts.

Upvotes: 1

Related Questions