1,博客表结构 Blog.js
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test',{ useUnifiedTopology: true , useNewUrlParser: true});
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
},
sort:{
type: mongoose.Schema.Types.ObjectId, ref: 'Sort'
}
});
var Blog = mongoose.model('Blog', blogSchema);
module.exports = Blog
2,分类表结构 Sort.js
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test',{ useUnifiedTopology: true , useNewUrlParser: true});
var Schema = mongoose.Schema;
var sortSchema = new Schema({
name:{type:String}
});
var Sort = mongoose.model('Sort', sortSchema);
module.exports = Sort
3,操作文件 api.js
const Blog = require('./Blog');
const Sort = require('./Sort');
async function cz(){
var sort1 = await Sort.findOne({name:"css"})
var blog1 = await Blog.find().populate('sort')
blog1.sort = sort1
await blog1.save()
}
cz()