Mongoose架构如何添加数组

时间:2016-12-07 08:53:50

标签: node.js mongodb

我想知道如何在moongoose架构中添加一个字符串数组。

我有以下代码,但它不起作用:

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

我在谈论users。你能帮忙吗?

3 个答案:

答案 0 :(得分:3)

将您在评论和主要帖子中所说的内容拼凑在一起,我无法帮助,但认为您错过了猫鼬的建模步骤。

首先定义架构:

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

然后你必须告诉mongoose:

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

然后您可以创建一个实例来将数据放入:

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

如果我错了,请发布有关哪些内容无效的更多信息。

答案 1 :(得分:0)

试试这个

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}

    });

答案 2 :(得分:0)

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