首页 \ 问答 \ 使用Node.js操作Mongoose / MongoDB数组(Manipulating Mongoose/MongoDB Array using Node.js)

使用Node.js操作Mongoose / MongoDB数组(Manipulating Mongoose/MongoDB Array using Node.js)

我注意到有关如何使用Mongoosejs操纵对象数组的文档和信息很少。

我有一个用户的以下模型/架构:

'use strict';

/**
 * Module Dependencies
 */

var bcrypt    = require('bcrypt-nodejs');
var crypto    = require('crypto');
var mongoose  = require('mongoose');

 /**
 * Custom types
 */
var ObjectId = mongoose.Schema.Types.ObjectId;

var userSchema = new mongoose.Schema({

  email: { type: String, unique: true, index: true },
  password: { type: String },
  type: { type: String, default: 'user' },
  facebook: { type: String, unique: true, sparse: true },
  twitter: { type: String, unique: true, sparse: true },
  google: { type: String, unique: true, sparse: true },
  github: { type: String, unique: true, sparse: true },
  tokens: Array,

  profile: {
    name: { type: String, default: '' },
    gender: { type: String, default: '' },
    location: { type: String, default: '' },
    website: { type: String, default: '' },
    picture: { type: String, default: '' },
    phone: {
      work: { type: String, default: '' },
      home: { type: String, default: '' },
      mobile: { type: String, default: '' }
    }
  },

  activity: {
    date_established: { type: Date, default: Date.now },
    last_logon: { type: Date, default: Date.now },
    last_updated: { type: Date }
  },

  resetPasswordToken: { type: String },
  resetPasswordExpires: { type: Date },

  verified: { type: Boolean, default: true },
  verifyToken: { type: String },

  enhancedSecurity: {
    enabled: { type: Boolean, default: false },
    type: { type: String },  // sms or totp
    token: { type: String },
    period: { type: Number },
    sms: { type: String },
    smsExpires: { type: Date }
  },

  friends: [{
    friend: { type: ObjectId, ref: 'User' },
    verified: { type: Boolean, default: false }
  }]

});

/* (...) some functions that aren't necessary to be shown here */

module.exports = mongoose.model('User', userSchema);

因此,您可以检查我在用户中定义的朋友,如下所示:

  friends: [{
    friend: { type: ObjectId, ref: 'User' },
    verified: { type: Boolean, default: false }
  }]

现在的问题是如何在Node.js脚本中添加,编辑和删除此数组?

BOTTOMLINE:如何使用Node.js和Mongoose.js操作MongoDB Schema中的数组? 我是否总是要创建一个Schema功能,还是可以直接访问它?

编辑(2014年7月13日):到目前为止,我已经创建了一个HTTP GET,它给了我这样的数组:

app.get('/workspace/friends/:userid', passportConf.isAuthenticated, function (req, res) {
  User.find({_id: req.params.userid}, function (err, items) {
      if (err) {
          return (err, null);
      }
      console.log(items[0].friends);
      res.json(items[0].friends);
  });
});

但这只返回一个friendIds数组,但是如果我想创建某种'/ workspace / friends /:userid / del /:friendid'POST或添加POST会怎样。 我似乎无法弄清楚如何完成这项工作。


I've noticed there's little documentation and info about how I should manipulate an array of objects using Mongoosejs.

I have the following model/Schema for an User:

'use strict';

/**
 * Module Dependencies
 */

var bcrypt    = require('bcrypt-nodejs');
var crypto    = require('crypto');
var mongoose  = require('mongoose');

 /**
 * Custom types
 */
var ObjectId = mongoose.Schema.Types.ObjectId;

var userSchema = new mongoose.Schema({

  email: { type: String, unique: true, index: true },
  password: { type: String },
  type: { type: String, default: 'user' },
  facebook: { type: String, unique: true, sparse: true },
  twitter: { type: String, unique: true, sparse: true },
  google: { type: String, unique: true, sparse: true },
  github: { type: String, unique: true, sparse: true },
  tokens: Array,

  profile: {
    name: { type: String, default: '' },
    gender: { type: String, default: '' },
    location: { type: String, default: '' },
    website: { type: String, default: '' },
    picture: { type: String, default: '' },
    phone: {
      work: { type: String, default: '' },
      home: { type: String, default: '' },
      mobile: { type: String, default: '' }
    }
  },

  activity: {
    date_established: { type: Date, default: Date.now },
    last_logon: { type: Date, default: Date.now },
    last_updated: { type: Date }
  },

  resetPasswordToken: { type: String },
  resetPasswordExpires: { type: Date },

  verified: { type: Boolean, default: true },
  verifyToken: { type: String },

  enhancedSecurity: {
    enabled: { type: Boolean, default: false },
    type: { type: String },  // sms or totp
    token: { type: String },
    period: { type: Number },
    sms: { type: String },
    smsExpires: { type: Date }
  },

  friends: [{
    friend: { type: ObjectId, ref: 'User' },
    verified: { type: Boolean, default: false }
  }]

});

/* (...) some functions that aren't necessary to be shown here */

module.exports = mongoose.model('User', userSchema);

So as you can check I defined Friends inside User like this:

  friends: [{
    friend: { type: ObjectId, ref: 'User' },
    verified: { type: Boolean, default: false }
  }]

Now the question is how can I add, edit and delete this array in a Node.js script?

BOTTOMLINE: How can I manipulate arrays that are inside MongoDB Schemas, using Node.js and Mongoose.js? Do I always have to create a Schema function or can I access it directly?

EDIT (13/07/2014): So far I've created a HTTP GET that gives me the array like this:

app.get('/workspace/friends/:userid', passportConf.isAuthenticated, function (req, res) {
  User.find({_id: req.params.userid}, function (err, items) {
      if (err) {
          return (err, null);
      }
      console.log(items[0].friends);
      res.json(items[0].friends);
  });
});

But this only returns an array of friendIds, but what if I want to create some sort of '/workspace/friends/:userid/del/:friendid' POST, or add POST. I can't seem to figure out how I can get this done.

更新时间:2022-01-30 16:01

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。