Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store object in mongoose schema?

In node.js I have three variables:

var name = 'Peter';
var surname = 'Bloom';
var addresses = [
    {street: 'W Division', city: 'Chicago'},
    {street: 'Beekman', city: 'New York'},
    {street: 'Florence', city: 'Los Angeles'},
];

And schema:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var personSchema = Schema({
  _id     : Number,
  name    : String,
  surname : String,
  addresses : ????
});

What type and how do I use it in schema? How is the best way for this?

like image 746
fogen Avatar asked Jun 24 '17 17:06

fogen


People also ask

How does a Mongoose store data?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

What does save () do in Mongoose?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

What is Mongoose schema explain with example?

A schema in Mongoose maps to a MongoDB collection and defines the format for all documents on that collection. All properties inside the schema must have an assigned SchemaType . For example, the name of our Person can be defined this way: const PersonSchema = new mongoose. Schema({ name: { type: String}, });

What is the difference between schema and model in Mongoose?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.


1 Answers

You must create another mongoose schema:

var address = Schema({ street: String, city: String});

And the type of addresses will be Array< address >

like image 182
Kenany Avatar answered Oct 01 '22 05:10

Kenany