新手编码员在这里提出了一个基本问题!我正在使用Mongoose进行项目,并且该项目的模型带有嵌套对象:
var mongoose = require("mongoose");
var commentSchema = mongoose.Schema({
text: String,
createdAt: { type: Date, default: Date.now },
author: { // AUTHOR CHANGED FROM STRING TO OBJECT
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model("Comment", commentSchema);
我正在尝试为数据库添加注释,因此我在函数中创建了一个名为“ seedcomments”的变量,并复制了模型中的代码,并更新了用于填充文本和作者的字符串用户名。
var mongoose = require("mongoose");
var Campground = require("./models/campground");
var Comment = require("./models/comment");
var seedcomments = [
{
text: "This place is great, but I wish there was internet",
createdAt: {type: Date, default: Date.now},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: "Homer"
}
}
];
async function seedDB(){
try {
await Campground.deleteMany({});
await Comment.deleteMany({});
for(const seed of seeds) {
let campground = await Campground.create(seed);
let comment = await Comment.create(seedcomments);
campground.comments.push(comment);
campground.save();
}
} catch(err) {
console.log(err);
}
}
module.exports = seedDB;
当确定“作者”和“ createdAt”部分的种子时,我只是不确定嵌套对象的正确语法是什么。我认为答案非常简单,但我在任何地方都找不到简单明了的解释。