我想知道我们如何在 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/