node.js - Mongoose 模式如何添加数组

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

我说的是用户。你能帮忙吗?

最佳答案

将您在评论和主要帖子中所说的内容拼凑在一起,我不禁认为您错过了 mongoose 的建模步骤。

首先定义模式:

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

如果我错了,请发布更多有关不起作用的信息。

关于node.js - Mongoose 模式如何添加数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41013039/

相关文章:

javascript - JSON 更新对象内部的数组

python - 使用 pymongo 和 flask 插入数据

node.js - NodeJS Passport

node.js - 如何通过 Grunt 配置目录递归 Sass 编译任务

node.js - 真实 iOS 设备上的 axios、react-native、nodejs 在 Xcode 中出现网络错误?

java - Fongo 2.1.0 不适用于 Mongo Java 驱动程序 3.2.8

node.js - NodeJS 多线程和大数据集

javascript - 从字符串中删除空格、连字符和括号

node.js - 使用 Mongoose 种群的正确方法是什么?

javascript - 使用 MongoDB map-reduce 生成扁平化文档