简体   繁体   English

猫鼬模式如何添加数组

[英]Mongoose schema how to add an array

I was wondering how can we add an array of string in a moongoose schema. 我想知道如何在Moongoose模式中添加字符串数组。

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 . 我说的是users Can you help? 你能帮我吗?

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. 如果我写错了,请发布更多有关无法正常工作的信息。

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}
    });

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}

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM