juliana Morales
juliana Morales

Reputation: 177

Mongoose schema how to add an array

I was wondering how can we add an array of string in a moongoose schema.

I have the following code but it is not working:

var message = new Schema({
    topic: String,
    content: String,
    restriction:String,
    sender:String,
    reciever:String,
    users:[String],
    read:{type: String, default: 'no'},
    like:{ type: Number, default: 0 },
    created_at: {type: Date, default: Date.now}
});

I am talking about users. Can you help?

Upvotes: 6

Views: 15037

Answers (3)

Paul
Paul

Reputation: 36349

Cobbling together what you said in your comments and the main post, I can't help but think you're missing the modeling step of mongoose.

First you define the schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var MessageSchema = new Schema({
    topic: String,
    content: String,
    restriction:String,
    sender:String,
    reciever:String,
    users:[String],
    read:{type: String, default: 'no'},
    like:{ type: Number, default: 0 },
    created_at: {type: Date, default: Date.now}
});

Then you have to tell mongoose about it:

const Message = mongoose.model('Message', MessageSchema);

Then you can create an instance to put data into:

mongoose.connect('mongodb://localhost:27017/mydb'); // assuming that's a working mongo instance
let message = new Message();
message.users.push('Juliana');
message.save((e,u) => { console.log('New user saved!'); });

If I'm wrong, please post more info about what's not working.

Upvotes: 6

Tushar Agarwal
Tushar Agarwal

Reputation: 365

var message = new Schema({
      topic: String,
      content: String,
      restriction:String,
      sender:String,
      reciever:String,
      users:[{
        type: String
      }],
      read:{type: String, default: 'no'},
      like:{ type: Number, default: 0 },
      created_at: {type: Date, default: Date.now}
    });

Upvotes: 1

Smita Ahinave
Smita Ahinave

Reputation: 1888

try this

var message = new Schema({
      topic: String,
      content: String,
      restriction:String,
      sender:String,
      reciever:String,
      users:[
      {name: String}],
      read:{type: String, default: 'no'},
      like:{ type: Number, default: 0 },
      created_at: {type: Date, default: Date.now}

    });

Upvotes: 0

Related Questions