我是node.js和MongoDB的新手.我正在使用Mongoose Library通过node.js访问MongoDB.
我有两个架构,书和作者.作者belongs_to一本书和书has_many作者.
我的模式中有这个:
var mongoose = require( 'mongoose' );
var Schema = mongoose.Schema;
var Book = new Schema({
title : String,
isbn : String,
authorId : [{ type: Schema.Types.ObjectId, ref: 'Author' }],
updated_at : Date
});
var Author = new Schema({
name : String,
updated_at : Date
});
mongoose.model( 'Book', Book );
mongoose.model( 'Author', Author );
mongoose.connect( 'mongodb://localhost/library' );
Run Code Online (Sandbox Code Playgroud)
问题是,当我从作为嵌入Book的Author中删除文档时,它将被删除而不检查参照完整性.我的情况是,如果作者文档嵌入了Book,则无法删除.Mongoose会自动检查书中嵌入的作者文档吗?可能吗?那怎么样?
假设我有这种数据......
data = [{
"_id" : "1",
"parentId" : "thisPostId",
"topLevelId" : "1",
"text" : "<p>comment</p>",
},
{
"_id" : "2",
"parentId" : "1",
"topLevelId" : "1",
"text" : "<p>reply to comment</p>",
},
{
"_id" : "3",
"parentId" : "2",
"topLevelId" : "1",
"text" : "<p>reply to reply to comment</p>",
},
{
"_id" : "4",
"parentId" : "3",
"topLevelId" : "1",
"text" : "<p>reply to reply to reply to comment</p>",
}]
Run Code Online (Sandbox Code Playgroud)
我需要删除评论及其所有孩子......
如果注释删除是_id:1,那么我需要一个数组["1","2","3","4"],,,然后我可以运行Coll.remove({_id:{$in:["1","2","3","4"]}}, callback);
如果注释要删除 …
我在我的模型中有这个代码:
ContentSchema.post( 'remove', function( item ) {
index.deleteObject( item._id )
})
Run Code Online (Sandbox Code Playgroud)
这是我的控制器中的内容:
Content.find( { user: user, _id: contentId } )
.remove( function ( err, count ) {
if ( err || count == 0 ) reject( new Error( "There was an error deleting that content from the stream." ) )
resolve( "Item removed from stream" )
})
Run Code Online (Sandbox Code Playgroud)
我希望当控制器中的函数运行时,模型中的函数应该发生.我可以在调试器中看到它根本不会触发.
我正在使用"mongoose": "3.8.23"和"mongoose-q": "0.0.16".
当DELETE请求发送到我的API时,我正在尝试删除模式的所有依赖项.删除没问题,但删除中间件,它应该是清理依赖项,似乎甚至没有被调用.
这是我的Customer架构:
var mongoose = require("mongoose"),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
var Order = require('./order');
var Customer = new Schema({
name: String,
telephone: Number,
address: String,
email: String,
seller: String
});
Customer.post('remove', function(next) {
Order.remove({ customer: this._id }).exec();
next();
});
Customer.plugin(passportLocalMongoose);
module.exports = mongoose.model("Customer", Customer);
Run Code Online (Sandbox Code Playgroud)
这是我的客户路线:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var isAuthenticated = require('./isAuthenticated');
var Customer = require('../models/customer');
var Order = require('../models/order');
// (...)
router.delete('/:customer_id', function(req, res) {
Customer.remove({ _id: req.params.customer_id …Run Code Online (Sandbox Code Playgroud)