MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come registrare e chiamare uno schema in mongoose

Supponendo che i due codici sopra siano in due file diversi e nella stessa cartella. e il nome del file Schema è comment.js

var mongoose = require('mongoose'),
  path = require('path'),
  config = require(path.resolve('./config/config')),
  Schema = mongoose.Schema;

var Commentsscheme = new Schema({
  articleid: {
    type: Schema.ObjectId
  },
  fromuser: {
    type: String
  },
  touser: {
    type: String
  },
  comment: {
    type: String
  }
});

module.exports = mongoose.model('Comment', Commentsscheme);

e in altri file js utilizzerai questo schema come segue

var path = require('path'),
  mongoose = require('mongoose'),
  passport = require('passport'),
  // here you need to put the path/name of the file so that module will load.
  Comments = require('comment.js');


/* ------ Inserting a comment  ------ */
exports.insertcomment = function (req, res) {
  var comments = new Comments(req.body);
  console.log(comments)
  comments.status = 1;
  var data = {};
  comments.save(function (err,resl) {
    if (err) {
      console.log(err);
      return err;
    } 
     data = { status: false, error_code: 0, message: 'Unable to insert' };
    if (resl) {
      data = { status: true, error_code: 0,result: resl, message: 'Inserted successfully' };
    }
      res.json(data);
  });
};